InternalCallVerifierVerifies values of objects/variables related to AUT calls Class: $.HelloWorldIT InternalCallVerifier EqualityVerifier
@Test public void testPing() throws Exception {
WebClient client=WebClient.create(endpointUrl + "/hello/echo/SierraTangoNevada");
Response r=client.accept("text/plain").get();
assertEquals(Response.Status.OK.getStatusCode(),r.getStatus());
String value=IOUtils.toString((InputStream)r.getEntity());
assertEquals("SierraTangoNevada",value);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testJsonRoundtrip() throws Exception {
List providers=new ArrayList();
providers.add(new org.codehaus.jackson.jaxrs.JacksonJsonProvider());
JsonBean inputBean=new JsonBean();
inputBean.setVal1("Maple");
WebClient client=WebClient.create(endpointUrl + "/hello/jsonBean",providers);
Response r=client.accept("application/json").type("application/json").post(inputBean);
assertEquals(Response.Status.OK.getStatusCode(),r.getStatus());
MappingJsonFactory factory=new MappingJsonFactory();
JsonParser parser=factory.createJsonParser((InputStream)r.getEntity());
JsonBean output=parser.readValueAs(JsonBean.class);
assertEquals("Maple",output.getVal2());
}
Class: $.HelloWorldImplTest InternalCallVerifier EqualityVerifier
@Test public void testSayHi(){
HelloWorldImpl helloWorldImpl=new HelloWorldImpl();
String response=helloWorldImpl.sayHi("Sam");
assertEquals("HelloWorldImpl not properly saying hi","Hello Sam",response);
}
Class: $.HelloWorldPortTypeImplTest InternalCallVerifier EqualityVerifier
@Test public void testSayHi(){
HelloWorldPortTypeImpl helloWorldPortTypeImpl=new HelloWorldPortTypeImpl();
String response=helloWorldPortTypeImpl.sayHi("Sam");
assertEquals("HelloWorldPortTypeImpl not properly saying hi","Hello Sam",response);
}
Class: demo.hw.server.HelloWorldImplTest InternalCallVerifier EqualityVerifier
@Test public void testGetUsers(){
HelloWorldImpl hwi=new HelloWorldImpl();
User mike=new UserImpl("Mike");
hwi.sayHiToUser(mike);
User george=new UserImpl("George");
hwi.sayHiToUser(george);
Map userMap=hwi.getUsers();
assertEquals("getUsers() not returning expected number of users",userMap.size(),2);
assertEquals("Expected user Mike not found","Mike",userMap.get(1).getName());
assertEquals("Expected user George not found","George",userMap.get(2).getName());
}
InternalCallVerifier EqualityVerifier
@Test public void testSayHiToUser(){
HelloWorldImpl hwi=new HelloWorldImpl();
User sam=new UserImpl("Sam");
String response=hwi.sayHiToUser(sam);
assertEquals("SayHiToUser isn't returning expected string","Hello Sam",response);
}
InternalCallVerifier EqualityVerifier
@Test public void testSayHi(){
HelloWorldImpl hwi=new HelloWorldImpl();
String response=hwi.sayHi("Bob");
assertEquals("SayHi isn't returning expected string","Hello Bob",response);
}
Class: org.apache.cxf.aegis.client.ClientServiceConfigTest InternalCallVerifier EqualityVerifier
@Test public void ordinaryParamNameTest() throws Exception {
ClientProxyFactoryBean proxyFac=new ClientProxyFactoryBean();
ReflectionServiceFactoryBean factory=new ReflectionServiceFactoryBean();
proxyFac.setServiceFactory(factory);
proxyFac.setDataBinding(new AegisDatabinding());
proxyFac.setAddress("local://Echo");
proxyFac.setBus(getBus());
Echo echo=proxyFac.create(Echo.class);
String boing=echo.simpleEcho("reflection");
assertEquals("reflection",boing);
}
Class: org.apache.cxf.aegis.custom.CustomBeansTest InternalCallVerifier IdentityVerifier
@Test public void testClientSetup() throws Exception {
JaxWsProxyFactoryBean clientFactory=new JaxWsProxyFactoryBean();
clientFactory.setAddress("local:not-really");
clientFactory.setServiceClass(Service.class);
AegisDatabinding dataBinding=new AegisDatabinding();
NoDefaultConstructorBeanTypeRegistrar beanRegistrar=new NoDefaultConstructorBeanTypeRegistrar();
beanRegistrar.setDataBinding(dataBinding);
beanRegistrar.register();
NoDefaultConstructorBeanKeyTypeRegistrar beanKeyRegistrar=new NoDefaultConstructorBeanKeyTypeRegistrar();
beanKeyRegistrar.setDataBinding(dataBinding);
beanKeyRegistrar.register();
clientFactory.setDataBinding(dataBinding);
clientFactory.create();
String uri=dataBinding.getAegisContext().getTypeMapping().getMappingIdentifierURI();
assertNotSame(DefaultTypeMapping.DEFAULT_MAPPING_URI,uri);
}
Class: org.apache.cxf.aegis.inheritance.ExceptionInheritanceTest UtilityVerifier BooleanVerifier InternalCallVerifier HybridVerifier
@Test public void testClient() throws Exception {
try {
client.throwException(true);
fail("No exception was thrown!");
}
catch ( WS1ExtendedException ex) {
Object sb=ex.getSimpleBean();
assertTrue(sb instanceof SimpleBean);
}
}
Class: org.apache.cxf.aegis.inheritance.intf.InterfaceInheritanceTest BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testClient() throws Exception {
ClientProxyFactoryBean proxyFac=new ClientProxyFactoryBean();
proxyFac.setAddress("local://IInterfaceService");
proxyFac.setBus(getBus());
setupAegis(proxyFac.getClientFactoryBean());
IInterfaceService client=proxyFac.create(IInterfaceService.class);
IChild child=client.getChild();
assertNotNull(child);
assertEquals("child",child.getChildName());
assertEquals("parent",child.getParentName());
IParent parent=client.getChildViaParent();
assertEquals("parent",parent.getParentName());
assertFalse(parent instanceof IChild);
IGrandChild grandChild=client.getGrandChild();
assertEquals("parent",grandChild.getParentName());
Document wsdl=getWSDLDocument("IInterfaceService");
assertValid("//xsd:complexType[@name='IGrandChild']",wsdl);
assertValid("//xsd:complexType[@name='IGrandChild']//xsd:element[@name='grandChildName']",wsdl);
assertValid("//xsd:complexType[@name='IGrandChild']//xsd:element[@name='childName'][1]",wsdl);
assertInvalid("//xsd:complexType[@name='IGrandChild']//xsd:element[@name='childName'][2]",wsdl);
assertValid("//xsd:complexType[@name='IChild']",wsdl);
assertValid("//xsd:complexType[@name='IParent']",wsdl);
assertInvalid("//xsd:complexType[@name='IChild'][@abstract='true']",wsdl);
}
Class: org.apache.cxf.aegis.integration.DOMMappingTest InternalCallVerifier EqualityVerifier
@Test public void testSimpleString() throws Exception {
String s=docClient.simpleStringReturn();
assertEquals("simple",s);
}
InternalCallVerifier EqualityVerifier
@Test public void testDocService() throws Exception {
Document doc=docClient.returnDocument();
Element rootElement=doc.getDocumentElement();
assertEquals("carrot",rootElement.getNodeName());
}
InternalCallVerifier EqualityVerifier
@Test public void testBeanCases() throws Exception {
BeanWithDOM bwd=docClient.getBeanWithDOM();
Element rootElement=bwd.getDocument().getDocumentElement();
assertEquals("carrot",rootElement.getNodeName());
}
Class: org.apache.cxf.aegis.integration.WrappedTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@org.junit.Ignore @Test public void testSubmitJDOMArray() throws Exception {
org.jdom.xpath.XPath jxpathWalrus=org.jdom.xpath.XPath.newInstance("/a:anyType/iam:walrus");
jxpathWalrus.addNamespace("a","urn:Array");
jxpathWalrus.addNamespace("iam","uri:iam");
jxpathWalrus.addNamespace("linux","uri:linux");
jxpathWalrus.addNamespace("planets","uri:planets");
invoke("Array","/org/apache/cxf/aegis/integration/anyTypeArrayJDOM.xml");
assertEquals("before items",arrayService.getBeforeValue());
assertEquals(3,arrayService.getJdomArray().length);
org.jdom.Element e=(org.jdom.Element)jxpathWalrus.selectSingleNode(arrayService.getJdomArray()[0]);
assertNotNull(e);
assertEquals("tusks",e.getText());
assertEquals("after items",arrayService.getAfterValue());
}
InternalCallVerifier EqualityVerifier
@Test public void testSubmitW3CArray() throws Exception {
addNamespace("a","urn:Array");
addNamespace("iam","uri:iam");
addNamespace("linux","uri:linux");
addNamespace("planets","uri:planets");
invoke("Array","/org/apache/cxf/aegis/integration/anyTypeArrayW3C.xml");
assertEquals("before items",arrayService.getBeforeValue());
assertEquals(3,arrayService.getW3cArray().length);
org.w3c.dom.Document e=arrayService.getW3cArray()[0];
assertValid("/iam:walrus",e);
assertEquals("after items",arrayService.getAfterValue());
}
Class: org.apache.cxf.aegis.namespaces.ExplicitPrefixTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testOnePrefix() throws Exception {
Map mappings=new HashMap();
mappings.put(URN_AEGIS_NAMESPACE_TEST,AEGIS_TEST_NAMESPACE_PREFIX_XYZZY);
ServiceAndMapping serviceAndMapping=setupService(NameServiceImpl.class,mappings);
Definition def=getWSDLDefinition("NameServiceImpl");
StringWriter wsdlSink=new StringWriter();
WSDLFactory.newInstance().newWSDLWriter().writeWSDL(def,wsdlSink);
org.w3c.dom.Document wsdlDoc=getWSDLDocument("NameServiceImpl");
Element rootElement=wsdlDoc.getDocumentElement();
addNamespace(AEGIS_TEST_NAMESPACE_PREFIX_XYZZY,URN_AEGIS_NAMESPACE_TEST);
assertXPathEquals("//namespace::xyzzy",URN_AEGIS_NAMESPACE_TEST,rootElement);
Element nameSchema=(Element)assertValid("//xsd:schema[@targetNamespace='urn:aegis:namespace:test']",rootElement).item(0);
Map namePrefixes=getNodeNamespaceDeclarations(nameSchema);
assertFalse(namePrefixes.containsKey("tns"));
Element serviceSchema=(Element)assertValid("//xsd:schema[@targetNamespace='http://impl.namespaces.aegis.cxf.apache.org']",rootElement).item(0);
Map servicePrefixes=getNodeNamespaceDeclarations(serviceSchema);
String testPrefix=lookupPrefix(servicePrefixes,URN_AEGIS_NAMESPACE_TEST);
assertEquals(AEGIS_TEST_NAMESPACE_PREFIX_XYZZY,testPrefix);
serviceAndMapping.getServer().destroy();
}
Class: org.apache.cxf.aegis.namespaces.NamespaceConfusionTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testNameNamespace() throws Exception {
org.w3c.dom.Document doc=getWSDLDocument("NameServiceImpl");
Element rootElement=doc.getDocumentElement();
Definition def=getWSDLDefinition("NameServiceImpl");
StringWriter sink=new StringWriter();
WSDLFactory.newInstance().newWSDLWriter().writeWSDL(def,sink);
NodeList aonNodes=assertValid("//xsd:complexType[@name='ArrayOfName']/xsd:sequence/xsd:element",doc);
Element arrayOfNameElement=(Element)aonNodes.item(0);
String typename=arrayOfNameElement.getAttribute("type");
String prefix=typename.split(":")[0];
String uri=getNamespaceForPrefix(rootElement,arrayOfNameElement,prefix);
assertNotNull(uri);
AegisType nameType=tm.getTypeCreator().createType(Name.class);
QName tmQname=nameType.getSchemaType();
assertEquals(tmQname.getNamespaceURI(),uri);
}
Class: org.apache.cxf.aegis.override.OverrideTypeTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testOverrideBean() throws Exception {
AegisDatabinding aegisDatabinding=new AegisDatabinding();
Set types=new HashSet();
types.add("org.apache.cxf.aegis.inheritance.Employee");
aegisDatabinding.setOverrideTypes(types);
DataReader dataReader=aegisDatabinding.createReader(XMLStreamReader.class);
InputStream employeeBytes=testUtilities.getResourceAsStream("/org/apache/cxf/aegis/override/employee.xml");
XMLInputFactory readerFactory=XMLInputFactory.newInstance();
XMLStreamReader reader=readerFactory.createXMLStreamReader(employeeBytes);
Object objectRead=dataReader.read(reader);
assertNotNull(objectRead);
assertTrue(objectRead instanceof Employee);
Employee e=(Employee)objectRead;
assertEquals("long",e.getDivision());
}
Class: org.apache.cxf.aegis.proxy.ProxyTest BooleanVerifier InternalCallVerifier
@Test public void testProxy() throws Exception {
ClientProxyFactoryBean proxyFac=new ClientProxyFactoryBean();
proxyFac.setAddress("local://HelloProxyService");
proxyFac.setBus(getBus());
AegisContext aegisContext=new AegisContext();
aegisContext.getBeanImplementationMap().put(Hello.class,MyHello.class.getName());
AegisDatabinding binding=new AegisDatabinding();
binding.setAegisContext(aegisContext);
setupAegis(proxyFac.getClientFactoryBean(),binding);
HelloProxyService client=proxyFac.create(HelloProxyService.class);
Hello h=client.sayHiWithProxy();
assertTrue(h instanceof MyHello);
}
Class: org.apache.cxf.aegis.standalone.SchemaAddinsTest InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testAegisTypeSchema() throws Exception {
AegisContext context=new AegisContext();
context.initialize();
XmlSchemaCollection collection=new XmlSchemaCollection();
context.addTypesSchemaDocument(collection);
XmlSchema[] schemas=collection.getXmlSchemas();
XmlSchema typeSchema=null;
for ( XmlSchema schema : schemas) {
if (AegisContext.UTILITY_TYPES_SCHEMA_NS.equals(schema.getTargetNamespace())) {
typeSchema=schema;
break;
}
}
assertNotNull(typeSchema);
assertNotSame(0,typeSchema.getItems().size());
XmlSchemaSerializer serializer=new XmlSchemaSerializer();
Document[] docs=serializer.serializeSchema(typeSchema,false);
testUtilities.assertValid("/xsd:schema/xsd:simpleType[@name='char']",docs[0]);
}
Class: org.apache.cxf.aegis.standalone.StandaloneReadTest InternalCallVerifier EqualityVerifier
@Test public void testCollectionReadXsiType() throws Exception {
context=new AegisContext();
Set roots=new HashSet();
java.lang.reflect.Type listStringType=ListStringInterface.class.getMethods()[0].getGenericReturnType();
roots.add(listStringType);
context.setRootClasses(roots);
context.initialize();
XMLStreamReader streamReader=testUtilities.getResourceAsXMLStreamReader("topLevelListWithXsiType.xml");
AegisReader reader=context.createXMLStreamReader();
Object something=reader.read(streamReader);
List correctAnswer=new ArrayList();
correctAnswer.add("cat");
correctAnswer.add("dog");
correctAnswer.add("hailstorm");
assertEquals(correctAnswer,something);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testCollectionReadNoXsiType() throws Exception {
context=new AegisContext();
Set roots=new HashSet();
java.lang.reflect.Type listStringType=ListStringInterface.class.getMethods()[0].getGenericReturnType();
roots.add(listStringType);
context.setRootClasses(roots);
context.initialize();
XMLStreamReader streamReader=testUtilities.getResourceAsXMLStreamReader("topLevelList.xml");
AegisReader reader=context.createXMLStreamReader();
QName magicTypeQName=new QName("urn:org.apache.cxf.aegis.types","ArrayOfString");
AegisType aegisRegisteredType=context.getTypeMapping().getType(magicTypeQName);
Object something=reader.read(streamReader,aegisRegisteredType);
List correctAnswer=new ArrayList();
correctAnswer.add("cat");
correctAnswer.add("dog");
correctAnswer.add("hailstorm");
assertEquals(correctAnswer,something);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testSimpleBeanRead() throws Exception {
context=new AegisContext();
Set rootClasses=new HashSet();
rootClasses.add(SimpleBean.class);
context.setRootClasses(rootClasses);
context.initialize();
XMLStreamReader streamReader=testUtilities.getResourceAsXMLStreamReader("simpleBean1.xml");
AegisReader reader=context.createXMLStreamReader();
Object something=reader.read(streamReader);
assertTrue(something instanceof SimpleBean);
SimpleBean simpleBean=(SimpleBean)something;
assertEquals("howdy",simpleBean.getHowdy());
}
BooleanVerifier InternalCallVerifier
@Test public void testBasicTypeRead() throws Exception {
context=new AegisContext();
context.initialize();
XMLStreamReader streamReader=testUtilities.getResourceAsXMLStreamReader("stringElement.xml");
AegisReader reader=context.createXMLStreamReader();
Object something=reader.read(streamReader);
assertTrue("ball-of-yarn".equals(something));
}
Class: org.apache.cxf.aegis.standalone.StandaloneWriteTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testTypeLookup() throws Exception {
context=new AegisContext();
context.initialize();
AegisType st=context.getTypeMapping().getType(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI,"string"));
assertNotNull(st);
assertEquals(st.getClass(),StringType.class);
}
Class: org.apache.cxf.aegis.type.array.FlatArrayTest InternalCallVerifier EqualityVerifier
@Test public void testFlatCollection() throws Exception {
ClientProxyFactoryBean proxyFac=new ClientProxyFactoryBean();
proxyFac.setDataBinding(new AegisDatabinding());
proxyFac.setAddress("local://FlatArray");
proxyFac.setBus(getBus());
FlatArrayServiceInterface client=proxyFac.create(FlatArrayServiceInterface.class);
BeanWithFlatCollection bwfc=new BeanWithFlatCollection();
bwfc.getValues().add(1);
bwfc.getValues().add(2);
bwfc.getValues().add(3);
bwfc=client.echoBeanWithFlatCollection(bwfc);
assertEquals(3,bwfc.getValues().size());
assertEquals(Integer.valueOf(1),bwfc.getValues().get(0));
assertEquals(Integer.valueOf(2),bwfc.getValues().get(1));
assertEquals(Integer.valueOf(3),bwfc.getValues().get(2));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testXmlConfigurationOfParameterTypeSchema() throws Exception {
NodeList typeList=assertValid("/wsdl:definitions/wsdl:types" + "/xsd:schema" + "[@targetNamespace='http://array.type.aegis.cxf.apache.org/']"+ "/xsd:complexType[@name=\"submitStringArray\"]"+ "/xsd:sequence/xsd:element"+ "[@name='array']",arrayWsdlDoc);
Element typeElement=(Element)typeList.item(0);
String nillableValue=typeElement.getAttribute("nillable");
assertTrue(nillableValue == null || "".equals(nillableValue) || "false".equals("nillableValue"));
String typeString=typeElement.getAttribute("type");
assertEquals("xsd:string",typeString);
typeList=assertValid("/wsdl:definitions/wsdl:types" + "/xsd:schema[@targetNamespace='http://array.type.aegis.cxf.apache.org']" + "/xsd:complexType[@name='BeanWithFlatArray']"+ "/xsd:sequence/xsd:element[@name='values']",arrayWsdlDoc);
typeElement=(Element)typeList.item(0);
assertValidBoolean("@type='xsd:int'",typeElement);
}
Class: org.apache.cxf.aegis.type.basic.BeanTest InternalCallVerifier EqualityVerifier
@Test public void testBean() throws Exception {
defaultContext();
BeanType type=new BeanType();
type.setTypeClass(SimpleBean.class);
type.setTypeMapping(mapping);
type.setSchemaType(new QName("urn:Bean","bean"));
ElementReader reader=new ElementReader(getResourceAsStream("bean1.xml"));
SimpleBean bean=(SimpleBean)type.readObject(reader,getContext());
assertEquals("bleh",bean.getBleh());
assertEquals("howdy",bean.getHowdy());
reader.getXMLStreamReader().close();
reader=new ElementReader(getResourceAsStream("bean2.xml"));
bean=(SimpleBean)type.readObject(reader,getContext());
assertEquals("bleh",bean.getBleh());
assertEquals("howdy",bean.getHowdy());
reader.getXMLStreamReader().close();
reader=new ElementReader(getResourceAsStream("bean7.xml"));
bean=(SimpleBean)type.readObject(reader,getContext());
assertEquals("",bean.getBleh());
assertEquals("howdy",bean.getHowdy());
reader.getXMLStreamReader().close();
bean.setBleh("bleh");
Element element=writeObjectToElement(type,bean,getContext());
assertValid("/b:root/b:bleh[text()='bleh']",element);
assertValid("/b:root/b:howdy[text()='howdy']",element);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testUnmappedProperty() throws Exception {
defaultContext();
String ns="urn:Bean";
BeanTypeInfo info=new BeanTypeInfo(SimpleBean.class,ns,false);
QName name=new QName(ns,"howdycustom");
info.mapElement("howdy",name);
info.setTypeMapping(mapping);
assertEquals("howdy",info.getPropertyDescriptorFromMappedName(name).getName());
BeanType type=new BeanType(info);
type.setTypeClass(SimpleBean.class);
type.setTypeMapping(mapping);
type.setSchemaType(new QName("urn:Bean","bean"));
ElementReader reader=new ElementReader(getResourceAsStream("bean3.xml"));
SimpleBean bean=(SimpleBean)type.readObject(reader,getContext());
assertEquals("howdy",bean.getHowdy());
assertNull(bean.getBleh());
reader.getXMLStreamReader().close();
Element element=writeObjectToElement(type,bean,getContext());
assertInvalid("/b:root/b:bleh",element);
assertValid("/b:root/b:howdycustom[text()='howdy']",element);
}
InternalCallVerifier EqualityVerifier
@Test public void testExtendedBean() throws Exception {
defaultContext();
BeanTypeInfo info=new BeanTypeInfo(ExtendedBean.class,"urn:Bean");
info.setTypeMapping(mapping);
BeanType type=new BeanType(info);
type.setTypeClass(ExtendedBean.class);
type.setTypeMapping(mapping);
type.setSchemaType(new QName("urn:Bean","bean"));
PropertyDescriptor[] pds=info.getPropertyDescriptors();
assertEquals(9,pds.length);
ExtendedBean bean=new ExtendedBean();
bean.setHowdy("howdy");
Element element=writeObjectToElement(type,bean,getContext());
assertValid("/b:root/b:howdy[text()='howdy']",element);
}
BooleanVerifier InternalCallVerifier
@Test public void testEnumBean() throws Exception {
defaultContext();
BeanType type=new BeanType();
type.setTypeClass(EnumBean.class);
type.setTypeMapping(mapping);
type.setSchemaType(new QName("urn:foo","EnumBean"));
assertTrue(type.getDependencies().isEmpty());
}
InternalCallVerifier EqualityVerifier
@Test public void testBeanWithXsiType() throws Exception {
defaultContext();
BeanType type=new BeanType();
type.setTypeClass(SimpleBean.class);
type.setTypeMapping(mapping);
type.setSchemaType(new QName("urn:Bean","bean"));
ElementReader reader=new ElementReader(getResourceAsStream("bean9.xml"));
Context ctx=getContext();
ctx.getGlobalContext().setReadXsiTypes(false);
SimpleBean bean=(SimpleBean)type.readObject(reader,ctx);
assertEquals("bleh",bean.getBleh());
assertEquals("howdy",bean.getHowdy());
reader.getXMLStreamReader().close();
Element element=writeObjectToElement(type,bean,getContext());
assertValid("/b:root/b:bleh[text()='bleh']",element);
assertValid("/b:root/b:howdy[text()='howdy']",element);
}
APIUtilityVerifier IterativeVerifier BranchVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCharMappings() throws Exception {
defaultContext();
BeanType type=(BeanType)mapping.getTypeCreator().createType(SimpleBean.class);
type.setTypeClass(SimpleBean.class);
type.setTypeMapping(mapping);
XmlSchema schema=newXmlSchema("urn:Bean");
type.writeSchema(schema);
XmlSchemaComplexType btype=(XmlSchemaComplexType)schema.getTypeByName("SimpleBean");
XmlSchemaSequence seq=(XmlSchemaSequence)btype.getParticle();
boolean charok=false;
for (int x=0; x < seq.getItems().size(); x++) {
XmlSchemaSequenceMember o=seq.getItems().get(x);
if (o instanceof XmlSchemaElement) {
XmlSchemaElement oe=(XmlSchemaElement)o;
if ("character".equals(oe.getName())) {
charok=true;
assertNotNull(oe.getSchemaTypeName());
assertTrue(oe.isNillable());
assertEquals(CharacterAsStringType.CHARACTER_AS_STRING_TYPE_QNAME,oe.getSchemaTypeName());
}
}
}
assertTrue(charok);
}
APIUtilityVerifier IterativeVerifier BranchVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testNillableAnnotation() throws Exception {
context=new AegisContext();
TypeCreationOptions config=new TypeCreationOptions();
config.setDefaultNillable(false);
config.setDefaultMinOccurs(1);
context.setTypeCreationOptions(config);
context.initialize();
mapping=context.getTypeMapping();
BeanType type=(BeanType)mapping.getTypeCreator().createType(BeanWithNillableItem.class);
type.setTypeClass(BeanWithNillableItem.class);
type.setTypeMapping(mapping);
XmlSchema schema=newXmlSchema("urn:Bean");
type.writeSchema(schema);
XmlSchemaComplexType btype=(XmlSchemaComplexType)schema.getTypeByName("BeanWithNillableItem");
XmlSchemaSequence seq=(XmlSchemaSequence)btype.getParticle();
boolean itemFound=false;
boolean itemNotNillableFound=false;
for (int x=0; x < seq.getItems().size(); x++) {
XmlSchemaSequenceMember o=seq.getItems().get(x);
if (o instanceof XmlSchemaElement) {
XmlSchemaElement oe=(XmlSchemaElement)o;
if ("item".equals(oe.getName())) {
itemFound=true;
assertTrue(oe.isNillable());
assertEquals(0,oe.getMinOccurs());
}
else if ("itemNotNillable".equals(oe.getName())) {
itemNotNillableFound=true;
assertFalse(oe.isNillable());
}
}
}
assertTrue(itemFound);
assertTrue(itemNotNillableFound);
}
InternalCallVerifier EqualityVerifier
@Test public void testAttributeMapDifferentNS() throws Exception {
defaultContext();
BeanTypeInfo info=new BeanTypeInfo(SimpleBean.class,"urn:Bean");
info.mapAttribute("howdy",new QName("urn:Bean2","howdy"));
info.mapAttribute("bleh",new QName("urn:Bean2","bleh"));
info.setTypeMapping(mapping);
BeanType type=new BeanType(info);
type.setTypeClass(SimpleBean.class);
type.setTypeMapping(mapping);
type.setSchemaType(new QName("urn:Bean","bean"));
ElementReader reader=new ElementReader(getResourceAsStream("bean8.xml"));
SimpleBean bean=(SimpleBean)type.readObject(reader,getContext());
assertEquals("bleh",bean.getBleh());
assertEquals("howdy",bean.getHowdy());
reader.getXMLStreamReader().close();
ByteArrayOutputStream bos=new ByteArrayOutputStream();
ElementWriter writer=new ElementWriter(bos,"root","urn:Bean");
type.writeObject(bean,writer,getContext());
writer.close();
writer.flush();
bos.close();
Document doc=StaxUtils.read(new ByteArrayInputStream(bos.toByteArray()));
Element element=doc.getDocumentElement();
addNamespace("b2","urn:Bean2");
assertValid("/b:root[@b2:bleh='bleh']",element);
assertValid("/b:root[@b2:howdy='howdy']",element);
}
APIUtilityVerifier IterativeVerifier BranchVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testByteMappings() throws Exception {
defaultContext();
BeanType type=(BeanType)mapping.getTypeCreator().createType(SimpleBean.class);
type.setTypeClass(SimpleBean.class);
type.setTypeMapping(mapping);
XmlSchema schema=newXmlSchema("urn:Bean");
type.writeSchema(schema);
XmlSchemaComplexType btype=(XmlSchemaComplexType)schema.getTypeByName("SimpleBean");
XmlSchemaSequence seq=(XmlSchemaSequence)btype.getParticle();
boolean littleByteOk=false;
boolean bigByteOk=false;
for (int x=0; x < seq.getItems().size(); x++) {
XmlSchemaSequenceMember o=seq.getItems().get(x);
if (o instanceof XmlSchemaElement) {
XmlSchemaElement oe=(XmlSchemaElement)o;
if ("littleByte".equals(oe.getName())) {
littleByteOk=true;
assertNotNull(oe.getSchemaTypeName());
assertEquals(Constants.XSD_BYTE,oe.getSchemaTypeName());
}
else if ("bigByte".equals(oe.getName())) {
bigByteOk=true;
assertNotNull(oe.getSchemaTypeName());
assertEquals(Constants.XSD_BYTE,oe.getSchemaTypeName());
}
}
}
assertTrue(littleByteOk);
assertTrue(bigByteOk);
SimpleBean bean=new SimpleBean();
bean.setBigByte(new Byte((byte)0xfe));
bean.setLittleByte((byte)0xfd);
Element element=writeObjectToElement(type,bean,getContext());
Byte bb=new Byte((byte)0xfe);
String bbs=bb.toString();
assertValid("/b:root/bz:bigByte[text()='" + bbs + "']",element);
ElementReader reader=new ElementReader(getResourceAsStream("byteBeans.xml"));
bean=(SimpleBean)type.readObject(reader,getContext());
assertEquals(-5,bean.getLittleByte());
assertEquals(25,bean.getBigByte().byteValue());
reader.getXMLStreamReader().close();
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testInterfaceBeans() throws Exception {
defaultContext();
BeanType type=new BeanType();
type.setTypeClass(SerializableBean.class);
type.setTypeMapping(mapping);
type.setSchemaType(new QName("urn:foo","SerializableBean"));
AegisType stringType=mapping.getType(String.class);
assertTrue(type.getDependencies().contains(stringType));
type=new BeanType();
type.setTypeClass(CloneableBean.class);
type.setTypeMapping(mapping);
type.setSchemaType(new QName("urn:foo","CloneableBean"));
assertEquals(1,type.getDependencies().size());
assertTrue(type.getDependencies().contains(stringType));
type=new BeanType();
type.setTypeClass(SimpleInterface.class);
type.setTypeMapping(mapping);
type.setSchemaType(new QName("urn:foo","SimpleInterface"));
assertEquals(1,type.getDependencies().size());
assertTrue(type.getDependencies().contains(stringType));
type=new BeanType();
type.setTypeClass(ExtendingInterface.class);
type.setTypeMapping(mapping);
type.setSchemaType(new QName("urn:foo","ExtendingInterface"));
Set dependencies=type.getDependencies();
assertEquals(2,dependencies.size());
dependencies.remove(stringType);
assertEquals(SimpleInterface.class,dependencies.iterator().next().getTypeClass());
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testAttributeMap() throws Exception {
defaultContext();
BeanTypeInfo info=new BeanTypeInfo(SimpleBean.class,"urn:Bean");
info.mapAttribute("howdy",new QName("urn:Bean","howdy"));
info.mapAttribute("bleh",new QName("urn:Bean","bleh"));
info.setTypeMapping(mapping);
BeanType type=new BeanType(info);
type.setTypeClass(SimpleBean.class);
type.setTypeMapping(mapping);
type.setSchemaType(new QName("urn:Bean","bean"));
ElementReader reader=new ElementReader(getResourceAsStream("bean4.xml"));
SimpleBean bean=(SimpleBean)type.readObject(reader,getContext());
assertEquals("bleh",bean.getBleh());
assertEquals("howdy",bean.getHowdy());
reader.getXMLStreamReader().close();
Element element=writeObjectToElement(type,bean,getContext());
assertValid("/b:root[@b:bleh='bleh']",element);
assertValid("/b:root[@b:howdy='howdy']",element);
XmlSchema schema=newXmlSchema("urn:Bean");
type.writeSchema(schema);
XmlSchemaComplexType stype=(XmlSchemaComplexType)schema.getTypeByName("bean");
boolean howdy=false;
boolean bleh=false;
for (int x=0; x < stype.getAttributes().size(); x++) {
XmlSchemaObject o=stype.getAttributes().get(x);
if (o instanceof XmlSchemaAttribute) {
XmlSchemaAttribute a=(XmlSchemaAttribute)o;
if ("howdy".equals(a.getName())) {
howdy=true;
}
if ("bleh".equals(a.getName())) {
bleh=true;
}
}
}
assertTrue(howdy);
assertTrue(bleh);
}
APIUtilityVerifier IterativeVerifier BranchVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testNillableInt() throws Exception {
defaultContext();
BeanTypeInfo info=new BeanTypeInfo(IntBean.class,"urn:Bean");
info.setTypeMapping(mapping);
BeanType type=new BeanType(info);
type.setTypeClass(IntBean.class);
type.setTypeMapping(mapping);
type.setSchemaType(new QName("urn:Bean","bean"));
XmlSchema schema=newXmlSchema("urn:Bean");
type.writeSchema(schema);
XmlSchemaComplexType btype=(XmlSchemaComplexType)schema.getTypeByName("bean");
XmlSchemaSequence seq=(XmlSchemaSequence)btype.getParticle();
boolean int1ok=false;
boolean int2ok=false;
for (int x=0; x < seq.getItems().size(); x++) {
XmlSchemaSequenceMember o=seq.getItems().get(x);
if (o instanceof XmlSchemaElement) {
XmlSchemaElement oe=(XmlSchemaElement)o;
if ("int1".equals(oe.getName())) {
int1ok=true;
assertTrue(oe.isNillable());
assertEquals(0,oe.getMinOccurs());
}
else if ("int2".equals(oe.getName())) {
int2ok=true;
assertEquals(0,oe.getMinOccurs());
assertFalse(oe.isNillable());
}
}
}
assertTrue(int1ok);
assertTrue(int2ok);
}
BooleanVerifier InternalCallVerifier
@Test public void testGetSetRequired() throws Exception {
defaultContext();
BeanType type=new BeanType();
type.setTypeClass(GoodBean.class);
type.setTypeMapping(mapping);
type.setSchemaType(new QName("urn:foo","BadBean"));
assertTrue(type.getTypeInfo().getElements().iterator().hasNext());
type=new BeanType();
type.setTypeClass(BadBean.class);
type.setTypeMapping(mapping);
type.setSchemaType(new QName("urn:foo","BadBean"));
assertFalse(type.getTypeInfo().getElements().iterator().hasNext());
type=new BeanType();
type.setTypeClass(BadBean2.class);
type.setTypeMapping(mapping);
type.setSchemaType(new QName("urn:foo","BadBean2"));
assertFalse(type.getTypeInfo().getElements().iterator().hasNext());
}
APIUtilityVerifier IterativeVerifier BranchVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testNillableIntMinOccurs1() throws Exception {
context=new AegisContext();
TypeCreationOptions config=new TypeCreationOptions();
config.setDefaultMinOccurs(1);
config.setDefaultNillable(false);
context.setTypeCreationOptions(config);
context.initialize();
mapping=context.getTypeMapping();
BeanType type=(BeanType)mapping.getTypeCreator().createType(IntBean.class);
type.setTypeClass(IntBean.class);
type.setTypeMapping(mapping);
XmlSchema schema=newXmlSchema("urn:Bean");
type.writeSchema(schema);
XmlSchemaComplexType btype=(XmlSchemaComplexType)schema.getTypeByName("IntBean");
XmlSchemaSequence seq=(XmlSchemaSequence)btype.getParticle();
boolean int1ok=false;
for (int x=0; x < seq.getItems().size(); x++) {
XmlSchemaSequenceMember o=seq.getItems().get(x);
if (o instanceof XmlSchemaElement) {
XmlSchemaElement oe=(XmlSchemaElement)o;
if ("int1".equals(oe.getName())) {
int1ok=true;
assertFalse(oe.isNillable());
assertEquals(1,oe.getMinOccurs());
}
}
}
assertTrue(int1ok);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testByteBean() throws Exception {
defaultContext();
BeanTypeInfo info=new BeanTypeInfo(ByteBean.class,"urn:Bean");
info.setTypeMapping(mapping);
BeanType type=new BeanType(info);
type.setTypeClass(ByteBean.class);
type.setTypeMapping(mapping);
type.setSchemaType(new QName("urn:Bean","bean"));
QName name=new QName("urn:Bean","data");
AegisType dataType=type.getTypeInfo().getType(name);
assertNotNull(dataType);
assertTrue(type.getTypeInfo().isNillable(name));
ByteBean bean=new ByteBean();
Element element=writeObjectToElement(type,bean,getContext());
addNamespace("xsi",Constants.URI_2001_SCHEMA_XSI);
assertValid("/b:root/b:data[@xsi:nil='true']",element);
XMLStreamReader sreader=StaxUtils.createXMLStreamReader(element);
bean=(ByteBean)type.readObject(new ElementReader(sreader),getContext());
assertNotNull(bean);
assertNull(bean.getData());
}
Class: org.apache.cxf.aegis.type.basic.DynamicProxyTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testDynamicProxyMissingAttribute() throws Exception {
BeanType type=new BeanType();
type.setTypeClass(IMyInterface.class);
type.setTypeMapping(mapping);
type.setSchemaType(new QName("urn:MyInterface","data"));
ElementReader reader=new ElementReader(getResourceAsStream("MyInterface.xml"));
IMyInterface data=(IMyInterface)type.readObject(reader,getContext());
assertEquals("junk",data.getName());
assertNull(data.getType());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testDynamicProxy() throws Exception {
BeanType type=new BeanType();
type.setTypeClass(IMyInterface.class);
type.setTypeMapping(mapping);
type.setSchemaType(new QName("urn:MyInterface","data"));
ElementReader reader=new ElementReader(getResourceAsStream("MyInterface.xml"));
IMyInterface data=(IMyInterface)type.readObject(reader,getContext());
assertEquals("junk",data.getName());
assertEquals(true,data.isUseless());
data.setName("bigjunk");
data.setUseless(false);
assertEquals("bigjunk",data.getName());
assertEquals(false,data.isUseless());
assertTrue(data.hashCode() != 0);
assertTrue(data.equals(data));
assertNotNull(data.toString());
assertEquals("foo",data.getFOO());
assertEquals(0,data.getNonSpecifiedInt());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testDynamicProxyNested() throws Exception {
BeanType type=new BeanType();
type.setTypeClass(IMyInterface.class);
type.setSchemaType(new QName("urn:MyInterface","myInterface"));
type.setTypeMapping(mapping);
BeanType type2=new BeanType();
type2.setTypeClass(IMyInterface2.class);
type2.setSchemaType(new QName("urn:MyInterface2","myInterface2"));
type2.setTypeMapping(mapping);
type2.getTypeInfo().mapType(new QName("urn:MyInterface","myInterface"),type);
ElementReader reader=new ElementReader(getResourceAsStream("MyInterface2.xml"));
IMyInterface2 data=(IMyInterface2)type2.readObject(reader,getContext());
assertNotNull(data.getMyInterface());
assertEquals("junk",data.getMyInterface().getName());
assertEquals(true,data.getMyInterface().isUseless());
}
Class: org.apache.cxf.aegis.type.encoded.SoapArrayTypeTest InternalCallVerifier EqualityVerifier
@Test public void testPartiallyTransmitted() throws Exception {
Context context=getContext();
ElementReader reader=new ElementReader(getClass().getResourceAsStream("arrayPartiallyTransmitted.xml"));
int[] numbers=(int[])createArrayType(int[].class).readObject(reader,context);
reader.getXMLStreamReader().close();
assertArrayEquals(new int[]{0,0,3,4,0},numbers);
numbers=readWriteReadRef("arrayPartiallyTransmitted.xml",int[].class);
assertArrayEquals(new int[]{0,0,3,4,0},numbers);
}
InternalCallVerifier EqualityVerifier
@Test public void testSimpleArray() throws Exception {
Context context=getContext();
ElementReader reader=new ElementReader(getClass().getResourceAsStream("arraySimple.xml"));
int[] numbers=(int[])createArrayType(int[].class).readObject(reader,context);
reader.getXMLStreamReader().close();
assertArrayEquals(new int[]{3,4},numbers);
numbers=readWriteReadRef("arraySimple.xml",int[].class);
assertArrayEquals(new int[]{3,4},numbers);
}
InternalCallVerifier EqualityVerifier
@Test public void testAnyTypeArray() throws Exception {
Context context=getContext();
ElementReader reader=new ElementReader(getClass().getResourceAsStream("arrayAnyType1.xml"));
Object[] objects=(Object[])createArrayType(Object[].class).readObject(reader,context);
reader.getXMLStreamReader().close();
assertArrayEquals(new Object[]{42,(float)42.42,"Forty Two"},objects);
reader=new ElementReader(getClass().getResourceAsStream("arrayAnyType2.xml"));
objects=(Object[])createArrayType(Object[].class).readObject(reader,context);
reader.getXMLStreamReader().close();
assertArrayEquals(new Object[]{42,new BigDecimal("42.42"),"Forty Two"},objects);
objects=readWriteReadRef("arrayAnyType1.xml",Object[].class);
assertArrayEquals(new Object[]{42,(float)42.42,"Forty Two"},objects);
objects=readWriteReadRef("arrayAnyType2.xml",Object[].class);
assertArrayEquals(new Object[]{42,new BigDecimal("42.42"),"Forty Two"},objects);
}
InternalCallVerifier EqualityVerifier
@Test public void testSquareArray() throws Exception {
Context context=getContext();
ElementReader reader=new ElementReader(getClass().getResourceAsStream("arraySquare.xml"));
String[][][] strings=(String[][][])createArrayType(String[][][].class).readObject(reader,context);
reader.getXMLStreamReader().close();
assertArrayEquals(ARRAY_2_3_4,strings);
strings=readWriteReadRef("arraySquare.xml",String[][][].class);
assertArrayEquals(ARRAY_2_3_4,strings);
}
InternalCallVerifier EqualityVerifier
@Test public void testArrayOfArrays() throws Exception {
Context context=getContext();
ElementReader reader=new ElementReader(getClass().getResourceAsStream("arrayArrayOfArrays1.xml"));
String[][][] strings=(String[][][])createArrayType(String[][][].class).readObject(reader,context);
reader.getXMLStreamReader().close();
assertArrayEquals(ARRAY_2_3_4,strings);
strings=readWriteReadRef("arrayArrayOfArrays1.xml",String[][][].class);
assertArrayEquals(ARRAY_2_3_4,strings);
}
InternalCallVerifier EqualityVerifier
@Test public void testUrTypeArray() throws Exception {
Context context=getContext();
ElementReader reader=new ElementReader(getClass().getResourceAsStream("arrayUrType1.xml"));
Object[] objects=(Object[])createArrayType(Object[].class).readObject(reader,context);
reader.getXMLStreamReader().close();
assertArrayEquals(new Object[]{42,(float)42.42,"Forty Two"},objects);
reader=new ElementReader(getClass().getResourceAsStream("arrayUrType2.xml"));
objects=(Object[])createArrayType(Object[].class).readObject(reader,context);
reader.getXMLStreamReader().close();
assertArrayEquals(Arrays.asList(objects).toString(),new Object[]{42,new BigDecimal("42.42"),"Forty Two"},objects);
}
Class: org.apache.cxf.aegis.type.java5.AnnotatedTypeTest APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testNillableAndMinOccurs(){
BeanType type=(BeanType)tm.getTypeCreator().createType(AnnotatedBean4.class);
AnnotatedTypeInfo info=(AnnotatedTypeInfo)type.getTypeInfo();
Iterator elements=info.getElements().iterator();
assertTrue(elements.hasNext());
QName element=elements.next();
if ("minOccursProperty".equals(element.getLocalPart())) {
assertEquals(1,info.getMinOccurs(element));
}
else {
assertFalse(info.isNillable(element));
}
assertTrue(elements.hasNext());
element=elements.next();
if ("minOccursProperty".equals(element.getLocalPart())) {
assertEquals(1,info.getMinOccurs(element));
}
else {
assertFalse(info.isNillable(element));
}
}
BooleanVerifier InternalCallVerifier
@Test public void testGetSetRequired() throws Exception {
BeanType type=new BeanType(new AnnotatedTypeInfo(tm,BadBean.class,"urn:foo",new TypeCreationOptions()));
type.setSchemaType(new QName("urn:foo","BadBean"));
assertFalse(type.getTypeInfo().getElements().iterator().hasNext());
}
APIUtilityVerifier BranchVerifier UtilityVerifier BooleanVerifier InternalCallVerifier HybridVerifier
@Test public void testType(){
AnnotatedTypeInfo info=new AnnotatedTypeInfo(tm,AnnotatedBean1.class,"urn:foo",new TypeCreationOptions());
Iterator elements=info.getElements().iterator();
assertTrue(elements.hasNext());
QName element=elements.next();
assertTrue(elements.hasNext());
AegisType custom=info.getType(element);
if ("bogusProperty".equals(element.getLocalPart())) {
assertTrue(custom instanceof StringType);
}
else if ("elementProperty".equals(element.getLocalPart())) {
assertTrue(custom instanceof CustomStringType);
}
else {
fail("Unexpected element name: " + element.getLocalPart());
}
element=elements.next();
assertFalse(elements.hasNext());
custom=info.getType(element);
if ("bogusProperty".equals(element.getLocalPart())) {
assertTrue(custom instanceof StringType);
}
else if ("elementProperty".equals(element.getLocalPart())) {
assertTrue(custom instanceof CustomStringType);
}
else {
fail("Unexpected element name: " + element.getLocalPart());
}
Iterator atts=info.getAttributes().iterator();
assertTrue(atts.hasNext());
atts.next();
assertFalse(atts.hasNext());
assertTrue(info.isExtensibleElements());
assertTrue(info.isExtensibleAttributes());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
/**
* Test if attributeProperty is correctly mapped to attProp by
* applying the xml mapping file .aegis.xml
*/
@Test public void testAegisType(){
BeanType type=(BeanType)tm.getTypeCreator().createType(AnnotatedBean3.class);
assertEquals(0,type.getTypeInfo().getAttributes().size());
Iterator itr=type.getTypeInfo().getElements().iterator();
assertTrue(itr.hasNext());
QName q=itr.next();
assertEquals("attProp",q.getLocalPart());
}
BooleanVerifier InternalCallVerifier
@Test public void testExtensibilityOff(){
BeanType type=(BeanType)tm.getTypeCreator().createType(AnnotatedBean4.class);
assertFalse(type.getTypeInfo().isExtensibleElements());
assertFalse(type.getTypeInfo().isExtensibleAttributes());
}
Class: org.apache.cxf.aegis.type.java5.CollectionTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testObjectDTO(){
tm=new DefaultTypeMapping(Constants.URI_2001_SCHEMA_XSD);
creator=new Java5TypeCreator();
creator.setConfiguration(new TypeCreationOptions());
tm.setTypeCreator(creator);
AegisType dto=creator.createType(ObjectDTO.class);
Set deps=dto.getDependencies();
assertFalse(deps.isEmpty());
AegisType type=deps.iterator().next();
assertTrue(type instanceof CollectionType);
CollectionType colType=(CollectionType)type;
deps=dto.getDependencies();
assertEquals(1,deps.size());
AegisType comType=colType.getComponentType();
assertEquals(Object.class,comType.getTypeClass());
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testRecursiveCollections() throws Exception {
Method m=CollectionService.class.getMethod("getStringCollections",new Class[0]);
AegisType type=creator.createType(m,-1);
tm.register(type);
assertTrue(type instanceof CollectionType);
CollectionType colType=(CollectionType)type;
QName componentName=colType.getSchemaType();
assertEquals("ArrayOfArrayOfString",componentName.getLocalPart());
type=colType.getComponentType();
assertNotNull(type);
assertTrue(type instanceof CollectionType);
CollectionType colType2=(CollectionType)type;
componentName=colType2.getSchemaType();
assertEquals("ArrayOfString",componentName.getLocalPart());
type=colType2.getComponentType();
assertTrue(type.getTypeClass().isAssignableFrom(String.class));
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testPDType() throws Exception {
PropertyDescriptor pd=Introspector.getBeanInfo(CollectionDTO.class,Object.class).getPropertyDescriptors()[0];
AegisType type=creator.createType(pd);
tm.register(type);
assertTrue(type instanceof CollectionType);
CollectionType colType=(CollectionType)type;
type=colType.getComponentType();
assertNotNull(type);
assertTrue(type.getTypeClass().isAssignableFrom(String.class));
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testType() throws Exception {
Method m=CollectionService.class.getMethod("getStrings",new Class[0]);
AegisType type=creator.createType(m,-1);
tm.register(type);
assertTrue(type instanceof CollectionType);
CollectionType colType=(CollectionType)type;
QName componentName=colType.getSchemaType();
assertEquals("ArrayOfString",componentName.getLocalPart());
assertEquals("ArrayOfString",componentName.getLocalPart());
type=colType.getComponentType();
assertNotNull(type);
assertTrue(type.getTypeClass().isAssignableFrom(String.class));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testCollectionDTO(){
tm=new DefaultTypeMapping(Constants.URI_2001_SCHEMA_XSD);
creator=new Java5TypeCreator();
creator.setConfiguration(new TypeCreationOptions());
tm.setTypeCreator(creator);
AegisType dto=creator.createType(CollectionDTO.class);
Set deps=dto.getDependencies();
AegisType type=deps.iterator().next();
assertTrue(type instanceof CollectionType);
CollectionType colType=(CollectionType)type;
deps=dto.getDependencies();
assertEquals(1,deps.size());
AegisType comType=colType.getComponentType();
assertEquals(String.class,comType.getTypeClass());
}
BooleanVerifier InternalCallVerifier
@Test public void testNestedMapType() throws Exception {
Method m=CollectionService.class.getMethod("mapOfMapWithStringAndPojo",new Class[]{Map.class});
AegisType type=creator.createType(m,0);
tm.register(type);
assertTrue(type instanceof MapType);
MapType mapType=(MapType)type;
AegisType valueType=mapType.getValueType();
assertFalse(valueType.getSchemaType().getLocalPart().contains("any"));
}
Class: org.apache.cxf.aegis.type.java5.CollectionTestsWithService APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
/**
* CXF-2017
* @throws Exception
*/
@Test public void testNestedMap() throws Exception {
Map> complexMap;
complexMap=new HashMap>();
Map innerMap=new HashMap();
BeanWithGregorianDate bean=new BeanWithGregorianDate();
bean.setName("shem bean");
bean.setId(42);
innerMap.put("firstBean",bean);
complexMap.put("firstKey",innerMap);
csi.mapOfMapWithStringAndPojo(complexMap);
Map> gotMap=impl.getLastComplexMap();
assertTrue(gotMap.containsKey("firstKey"));
Map v=gotMap.get("firstKey");
BeanWithGregorianDate b=v.get("firstBean");
assertNotNull(b);
}
InternalCallVerifier EqualityVerifier
@Test public void returnValueIsCollectionOfArraysOfAny(){
Collection r=csi.returnCollectionOfDOMFragments();
assertEquals(2,r.size());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void returnValueIsCollectionOfArrays(){
Collection doubleDouble=csi.returnCollectionOfPrimitiveArrays();
assertEquals(2,doubleDouble.size());
double[][] data=new double[2][];
for ( double[] array : doubleDouble) {
if (array.length == 3) {
data[0]=array;
}
else {
data[1]=array;
}
}
assertNotNull(data[0]);
assertNotNull(data[1]);
assertEquals(3.14,data[0][0],.0001);
assertEquals(2,data[0][1],.0001);
assertEquals(-666.6,data[0][2],.0001);
assertEquals(-666.6,data[1][0],.0001);
assertEquals(3.14,data[1][1],.0001);
assertEquals(2.0,data[1][2],.0001);
}
InternalCallVerifier EqualityVerifier
@Test public void testListTypes() throws Exception {
SortedSet strings=new TreeSet();
strings.add("Able");
strings.add("Baker");
String first=csi.takeSortedStrings(strings);
assertEquals("Able",first);
HashSet hashedSet=new HashSet();
hashedSet.addAll(strings);
String countString=csi.takeUnsortedSet(hashedSet);
assertEquals("2",countString);
}
Class: org.apache.cxf.aegis.type.java5.ConfigurationTest BooleanVerifier InternalCallVerifier
@Test public void testNillableDefaultTrue() throws Exception {
config.setDefaultNillable(true);
AegisType type=tm.getTypeCreator().createType(AnnotatedBean1.class);
BeanTypeInfo info=((BeanType)type).getTypeInfo();
assertTrue(info.isNillable(new QName(info.getDefaultNamespace(),"bogusProperty")));
}
BooleanVerifier InternalCallVerifier
@Test public void testExtensibleDefaultFalse() throws Exception {
config.setDefaultExtensibleElements(false);
config.setDefaultExtensibleAttributes(false);
AegisType type=tm.getTypeCreator().createType(AnnotatedBean1.class);
BeanTypeInfo info=((BeanType)type).getTypeInfo();
assertFalse(info.isExtensibleElements());
assertFalse(info.isExtensibleAttributes());
}
InternalCallVerifier EqualityVerifier
@Test public void testMinOccursDefault0() throws Exception {
config.setDefaultMinOccurs(0);
AegisType type=tm.getTypeCreator().createType(AnnotatedBean1.class);
BeanTypeInfo info=((BeanType)type).getTypeInfo();
assertEquals(info.getMinOccurs(new QName(info.getDefaultNamespace(),"bogusProperty")),0);
}
BooleanVerifier InternalCallVerifier
@Test public void testNillableDefaultFalse() throws Exception {
config.setDefaultNillable(false);
AegisType type=tm.getTypeCreator().createType(AnnotatedBean1.class);
BeanTypeInfo info=((BeanType)type).getTypeInfo();
assertFalse(info.isNillable(new QName(info.getDefaultNamespace(),"bogusProperty")));
}
InternalCallVerifier EqualityVerifier
@Test public void testMinOccursDefault1() throws Exception {
config.setDefaultMinOccurs(1);
AegisType type=tm.getTypeCreator().createType(AnnotatedBean1.class);
BeanTypeInfo info=((BeanType)type).getTypeInfo();
assertEquals(info.getMinOccurs(new QName(info.getDefaultNamespace(),"bogusProperty")),1);
}
BooleanVerifier InternalCallVerifier
@Test public void testExtensibleDefaultTrue() throws Exception {
config.setDefaultExtensibleElements(true);
config.setDefaultExtensibleAttributes(true);
AegisType type=tm.getTypeCreator().createType(AnnotatedBean1.class);
BeanTypeInfo info=((BeanType)type).getTypeInfo();
assertTrue(info.isExtensibleElements());
assertTrue(info.isExtensibleAttributes());
}
Class: org.apache.cxf.aegis.type.java5.EnumTypeTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testType() throws Exception {
EnumType type=new EnumType();
type.setTypeClass(SmallEnum.class);
type.setSchemaType(new QName("urn:test","test"));
tm.register(type);
Element element=writeObjectToElement(type,SmallEnum.VALUE1,getContext());
assertEquals("VALUE1",element.getTextContent());
XMLStreamReader xreader=StaxUtils.createXMLStreamReader(element);
ElementReader reader=new ElementReader(xreader);
Object value=type.readObject(reader,getContext());
assertEquals(SmallEnum.VALUE1,value);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testXFireTypeAttributeOnEnum() throws Exception {
AegisType type=tm.getTypeCreator().createType(XFireTestEnum.class);
assertEquals("urn:xfire:foo",type.getSchemaType().getNamespaceURI());
assertTrue(type instanceof EnumType);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testNillable() throws Exception {
AegisType type=tm.getTypeCreator().createType(EnumBean.class);
tm.register(type);
Element root=writeObjectToElement(type,new EnumBean(),getContext());
ElementReader reader=new ElementReader(StaxUtils.createXMLStreamReader(root));
Object value=type.readObject(reader,getContext());
assertTrue(value instanceof EnumBean);
EnumBean bean=(EnumBean)value;
assertNull(bean.getCurrency());
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testTypeAttributeOnEnum() throws Exception {
AegisType type=tm.getTypeCreator().createType(TestEnum.class);
assertEquals("urn:xfire:foo",type.getSchemaType().getNamespaceURI());
assertTrue(type instanceof EnumType);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testJaxbTypeAttributeOnEnum() throws Exception {
AegisType type=tm.getTypeCreator().createType(JaxbTestEnum.class);
assertEquals("urn:xfire:foo",type.getSchemaType().getNamespaceURI());
assertTrue(type instanceof EnumType);
}
BooleanVerifier InternalCallVerifier
@Test public void testAutoCreation() throws Exception {
AegisType type=tm.getTypeCreator().createType(SmallEnum.class);
assertTrue(type instanceof EnumType);
}
Class: org.apache.cxf.aegis.type.java5.JaxbTypeTest APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testNillableAndMinOccurs(){
BeanType type=(BeanType)tm.getTypeCreator().createType(JaxbBean4.class);
AnnotatedTypeInfo info=(AnnotatedTypeInfo)type.getTypeInfo();
Iterator elements=info.getElements().iterator();
assertTrue(elements.hasNext());
QName element=elements.next();
if ("minOccursProperty".equals(element.getLocalPart())) {
assertEquals(1,info.getMinOccurs(element));
}
else {
assertFalse(info.isNillable(element));
}
assertTrue(elements.hasNext());
element=elements.next();
if ("minOccursProperty".equals(element.getLocalPart())) {
assertEquals(1,info.getMinOccurs(element));
}
else {
assertFalse(info.isNillable(element));
}
}
APIUtilityVerifier BranchVerifier UtilityVerifier BooleanVerifier InternalCallVerifier HybridVerifier
@Test public void testType(){
AnnotatedTypeInfo info=new AnnotatedTypeInfo(tm,JaxbBean1.class,"urn:foo",new TypeCreationOptions());
Iterator elements=info.getElements().iterator();
assertTrue(elements.hasNext());
QName element=elements.next();
assertTrue(elements.hasNext());
AegisType custom=info.getType(element);
if ("bogusProperty".equals(element.getLocalPart())) {
assertTrue(custom instanceof StringType);
}
else if ("elementProperty".equals(element.getLocalPart())) {
assertTrue(custom instanceof CustomStringType);
}
else {
fail("Unexpected element name: " + element.getLocalPart());
}
element=elements.next();
assertFalse(elements.hasNext());
custom=info.getType(element);
if ("bogusProperty".equals(element.getLocalPart())) {
assertTrue(custom instanceof StringType);
}
else if ("elementProperty".equals(element.getLocalPart())) {
assertTrue(custom instanceof CustomStringType);
}
else {
fail("Unexpected element name: " + element.getLocalPart());
}
Iterator atts=info.getAttributes().iterator();
assertTrue(atts.hasNext());
atts.next();
assertFalse(atts.hasNext());
assertTrue(info.isExtensibleElements());
assertTrue(info.isExtensibleAttributes());
}
BooleanVerifier InternalCallVerifier
@Test public void testExtensibilityOff(){
BeanType type=(BeanType)tm.getTypeCreator().createType(JaxbBean4.class);
assertFalse(type.getTypeInfo().isExtensibleElements());
assertFalse(type.getTypeInfo().isExtensibleAttributes());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetSetRequired() throws Exception {
BeanType type=new BeanType(new AnnotatedTypeInfo(tm,BadBean.class,"urn:foo",new TypeCreationOptions()));
type.setSchemaType(new QName("urn:foo","BadBean"));
assertEquals(0,type.getTypeInfo().getElements().size());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
/**
* Test if attributeProperty is correctly mapped to attProp by
* applying the xml mapping file .aegis.xml
*/
@Test public void testAegisType(){
BeanType type=(BeanType)tm.getTypeCreator().createType(JaxbBean3.class);
assertEquals(0,type.getTypeInfo().getAttributes().size());
Iterator itr=type.getTypeInfo().getElements().iterator();
assertTrue(itr.hasNext());
QName q=itr.next();
assertEquals("attProp",q.getLocalPart());
}
Class: org.apache.cxf.aegis.type.java5.MapTest BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testPDType() throws Exception {
PropertyDescriptor pd=Introspector.getBeanInfo(MapDTO.class,Object.class).getPropertyDescriptors()[0];
AegisType type=creator.createType(pd);
tm.register(type);
assertTrue(type instanceof MapType);
MapType mapType=(MapType)type;
QName keyName=mapType.getKeyName();
assertNotNull(keyName);
type=mapType.getKeyType();
assertNotNull(type);
assertTrue(type.getTypeClass().isAssignableFrom(String.class));
type=mapType.getValueType();
assertNotNull(type);
assertTrue(type.getTypeClass().isAssignableFrom(Integer.class));
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testRecursiveType() throws Exception {
Method m=MapService.class.getMethod("getMapOfCollections",new Class[0]);
AegisType type=creator.createType(m,-1);
tm.register(type);
assertTrue(type instanceof MapType);
MapType mapType=(MapType)type;
QName keyName=mapType.getKeyName();
assertNotNull(keyName);
type=mapType.getKeyType();
assertNotNull(type);
assertTrue(type instanceof CollectionType);
assertEquals(String.class,((CollectionType)type).getComponentType().getTypeClass());
type=mapType.getValueType();
assertNotNull(type);
assertTrue(type instanceof CollectionType);
assertEquals(Double.class,((CollectionType)type).getComponentType().getTypeClass());
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testType() throws Exception {
Method m=MapService.class.getMethod("getMap",new Class[0]);
AegisType type=creator.createType(m,-1);
tm.register(type);
assertTrue(type instanceof MapType);
MapType mapType=(MapType)type;
QName keyName=mapType.getKeyName();
assertNotNull(keyName);
type=mapType.getKeyType();
assertNotNull(type);
assertTrue(type.getTypeClass().isAssignableFrom(String.class));
type=mapType.getValueType();
assertNotNull(type);
assertTrue(type.getTypeClass().isAssignableFrom(Integer.class));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testMapDTO(){
tm=new DefaultTypeMapping();
creator=new Java5TypeCreator();
creator.setConfiguration(new TypeCreationOptions());
tm.setTypeCreator(creator);
AegisType dto=creator.createType(MapDTO.class);
Set deps=dto.getDependencies();
AegisType type=deps.iterator().next();
assertTrue(type instanceof MapType);
MapType mapType=(MapType)type;
deps=dto.getDependencies();
assertEquals(1,deps.size());
type=mapType.getKeyType();
assertNotNull(type);
assertTrue(type.getTypeClass().isAssignableFrom(String.class));
type=mapType.getValueType();
assertNotNull(type);
assertTrue(type.getTypeClass().isAssignableFrom(Integer.class));
}
Class: org.apache.cxf.aegis.type.java5.XFireTypeTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
/**
* Test if attributeProperty is correctly mapped to attProp by
* applying the xml mapping file .aegis.xml
*/
@Test public void testAegisType(){
BeanType type=(BeanType)tm.getTypeCreator().createType(XFireBean3.class);
assertEquals(0,type.getTypeInfo().getAttributes().size());
Iterator itr=type.getTypeInfo().getElements().iterator();
assertTrue(itr.hasNext());
QName q=itr.next();
assertEquals("attProp",q.getLocalPart());
}
BooleanVerifier InternalCallVerifier
@Test public void testExtensibilityOff(){
BeanType type=(BeanType)tm.getTypeCreator().createType(XFireBean4.class);
assertFalse(type.getTypeInfo().isExtensibleElements());
assertFalse(type.getTypeInfo().isExtensibleAttributes());
}
APIUtilityVerifier BranchVerifier UtilityVerifier BooleanVerifier InternalCallVerifier HybridVerifier
@Test public void testType(){
AnnotatedTypeInfo info=new AnnotatedTypeInfo(tm,XFireBean1.class,"urn:foo",new TypeCreationOptions());
Iterator elements=info.getElements().iterator();
assertTrue(elements.hasNext());
QName element=elements.next();
assertTrue(elements.hasNext());
AegisType custom=info.getType(element);
if ("bogusProperty".equals(element.getLocalPart())) {
assertTrue(custom instanceof StringType);
}
else if ("elementProperty".equals(element.getLocalPart())) {
assertTrue(custom instanceof CustomStringType);
}
else {
fail("Unexpected element name: " + element.getLocalPart());
}
element=elements.next();
assertFalse(elements.hasNext());
custom=info.getType(element);
if ("bogusProperty".equals(element.getLocalPart())) {
assertTrue(custom instanceof StringType);
}
else if ("elementProperty".equals(element.getLocalPart())) {
assertTrue(custom instanceof CustomStringType);
}
else {
fail("Unexpected element name: " + element.getLocalPart());
}
Iterator atts=info.getAttributes().iterator();
assertTrue(atts.hasNext());
atts.next();
assertFalse(atts.hasNext());
assertTrue(info.isExtensibleElements());
assertTrue(info.isExtensibleAttributes());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetSetRequired() throws Exception {
BeanType type=new BeanType(new AnnotatedTypeInfo(tm,BadBean.class,"urn:foo",new TypeCreationOptions()));
type.setSchemaType(new QName("urn:foo","BadBean"));
assertEquals(0,type.getTypeInfo().getElements().size());
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testNillableAndMinOccurs(){
BeanType type=(BeanType)tm.getTypeCreator().createType(XFireBean4.class);
AnnotatedTypeInfo info=(AnnotatedTypeInfo)type.getTypeInfo();
Iterator elements=info.getElements().iterator();
assertTrue(elements.hasNext());
QName element=elements.next();
if ("minOccursProperty".equals(element.getLocalPart())) {
assertEquals(1,info.getMinOccurs(element));
}
else {
assertFalse(info.isNillable(element));
}
assertTrue(elements.hasNext());
element=elements.next();
if ("minOccursProperty".equals(element.getLocalPart())) {
assertEquals(1,info.getMinOccurs(element));
}
else {
assertFalse(info.isNillable(element));
}
}
Class: org.apache.cxf.aegis.type.java5.XFireXmlParamTypeTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testType() throws Exception {
Method m=CustomTypeService.class.getMethod("doFoo",new Class[]{String.class});
AegisType type=creator.createType(m,0);
tm.register(type);
assertTrue(type instanceof CustomStringType);
assertEquals(new QName("urn:xfire:foo","custom"),type.getSchemaType());
type=creator.createType(m,-1);
tm.register(type);
assertTrue(type instanceof CustomStringType);
assertEquals(new QName("urn:xfire:foo","custom"),type.getSchemaType());
}
Class: org.apache.cxf.aegis.type.java5.XmlParamTypeTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testType() throws Exception {
Method m=CustomTypeService.class.getMethod("doFoo",new Class[]{String.class});
AegisType type=creator.createType(m,0);
tm.register(type);
assertTrue(type instanceof CustomStringType);
type=creator.createType(m,-1);
tm.register(type);
assertTrue(type instanceof CustomStringType);
assertEquals(new QName("urn:xfire:foo","custom"),type.getSchemaType());
}
Class: org.apache.cxf.aegis.type.java5.map.StudentTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testReturnMapDocLiteral() throws Exception {
JaxWsServerFactoryBean sf=new JaxWsServerFactoryBean();
sf.setServiceClass(StudentServiceDocLiteral.class);
sf.setServiceBean(new StudentServiceDocLiteralImpl());
sf.setAddress("local://StudentServiceDocLiteral");
setupAegis(sf);
Server server=sf.create();
server.getEndpoint().getInInterceptors().add(new LoggingInInterceptor());
server.getEndpoint().getOutInterceptors().add(new LoggingOutInterceptor());
server.start();
JaxWsProxyFactoryBean proxyFac=new JaxWsProxyFactoryBean();
proxyFac.setAddress("local://StudentServiceDocLiteral");
proxyFac.setBus(getBus());
setupAegis(proxyFac.getClientFactoryBean());
proxyFac.getInInterceptors().add(new LoggingInInterceptor());
proxyFac.getOutInterceptors().add(new LoggingOutInterceptor());
StudentServiceDocLiteral clientInterface=proxyFac.create(StudentServiceDocLiteral.class);
Map fullMap=clientInterface.getStudentsMap();
assertNotNull(fullMap);
Student one=fullMap.get(Long.valueOf(1));
assertNotNull(one);
assertEquals("Student1",one.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testReturnMap() throws Exception {
JaxWsServerFactoryBean sf=new JaxWsServerFactoryBean();
sf.setServiceClass(StudentService.class);
sf.setServiceBean(new StudentServiceImpl());
sf.setAddress("local://StudentService");
setupAegis(sf);
Server server=sf.create();
server.start();
JaxWsProxyFactoryBean proxyFac=new JaxWsProxyFactoryBean();
proxyFac.setAddress("local://StudentService");
proxyFac.setBus(getBus());
setupAegis(proxyFac.getClientFactoryBean());
StudentService clientInterface=proxyFac.create(StudentService.class);
Map fullMap=clientInterface.getStudentsMap();
assertNotNull(fullMap);
Student one=fullMap.get(Long.valueOf(1));
assertNotNull(one);
assertEquals("Student1",one.getName());
Map wildMap=clientInterface.getWildcardMap();
assertEquals("valuestring",wildMap.get("keystring"));
}
Class: org.apache.cxf.aegis.type.map.MapsTest APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testNull() throws Exception {
ObjectWithAMap obj1=clientInterface.returnObjectWithAMap();
assertNull(obj1.getTheMap().get("raw"));
Map m=clientInterface.getMapLongToString();
String str2=m.get(Long.valueOf(2));
assertNull("value for 2 should be null, was " + str2,str2);
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testObjectsWithMaps() throws Exception {
ObjectWithAMap obj1=clientInterface.returnObjectWithAMap();
ObjectWithAMapNs2 obj2=clientInterface.returnObjectWithAMapNs2();
assertNotNull(obj1);
assertNotNull(obj2);
assertNotNull(obj1.getTheMap());
assertNotNull(obj2.getTheMap());
assertEquals(3,obj1.getTheMap().size());
assertEquals(3,obj2.getTheMap().size());
assertTrue(obj1.getTheMap().get("rainy"));
assertTrue(obj2.getTheMap().get("rainy"));
assertFalse(obj1.getTheMap().get("sunny"));
assertFalse(obj2.getTheMap().get("sunny"));
assertFalse(obj2.getTheMap().get("cloudy"));
}
InternalCallVerifier EqualityVerifier
@Test public void testInvocations() throws Exception {
Map lts=clientInterface.getMapLongToString();
assertEquals("twenty-seven",lts.get(Long.valueOf(27)));
}
Class: org.apache.cxf.aegis.type.streams.XMLStreamReaderMappingTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testReadStream() throws Exception {
InputStream is=getResourceAsStream("bean1.xml");
XMLInputFactory inputFactory=XMLInputFactory.newInstance();
XMLStreamReader inputReader=inputFactory.createXMLStreamReader(is);
AegisReader reader=context.createXMLStreamReader();
Object what=reader.read(inputReader);
assertTrue(what instanceof XMLStreamReader);
XMLStreamReader beanReader=(XMLStreamReader)what;
beanReader.nextTag();
assertEquals("bleh",beanReader.getLocalName());
}
Class: org.apache.cxf.aegis.xmlconfig.NillableTest APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testXmlConfigurationOfParameterTypeSchema() throws Exception {
NodeList typeList=assertValid("/wsdl:definitions/wsdl:types" + "/xsd:schema[@targetNamespace='urn:nillable']" + "/xsd:complexType[@name=\"submitStringArray\"]"+ "/xsd:sequence/xsd:element"+ "[@name='array']",arrayWsdlDoc);
Element typeElement=(Element)typeList.item(0);
String nillableValue=typeElement.getAttribute("nillable");
assertTrue(nillableValue == null || "".equals(nillableValue) || "false".equals("nillableValue"));
typeList=assertValid("/wsdl:definitions/wsdl:types" + "/xsd:schema[@targetNamespace='urn:nillable']" + "/xsd:complexType[@name=\"takeNotNillableString\"]"+ "/xsd:sequence/xsd:element[@name='string']",arrayWsdlDoc);
typeElement=(Element)typeList.item(0);
nillableValue=typeElement.getAttribute("nillable");
assertTrue(nillableValue == null || "".equals(nillableValue) || "false".equals("nillableValue"));
}
Class: org.apache.cxf.attachment.AttachmentDeserializerTest APIUtilityVerifier IterativeVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testLazyAttachmentCollection() throws Exception {
InputStream is=getClass().getResourceAsStream("mimedata2");
String ct="multipart/related; type=\"application/xop+xml\"; " + "start=\"\"; " + "start-info=\"text/xml; charset=utf-8\"; "+ "boundary=\"----=_Part_4_701508.1145579811786\"";
msg.put(Message.CONTENT_TYPE,ct);
msg.setContent(InputStream.class,is);
AttachmentDeserializer deserializer=new AttachmentDeserializer(msg);
deserializer.initializeAttachments();
InputStream attBody=msg.getContent(InputStream.class);
assertTrue(attBody != is);
assertTrue(attBody instanceof DelegatingInputStream);
attBody.close();
assertEquals(2,msg.getAttachments().size());
List cidlist=new ArrayList();
cidlist.add("xfire_logo.jpg");
cidlist.add("xfire_logo2.jpg");
for (Iterator it=msg.getAttachments().iterator(); it.hasNext(); ) {
Attachment a=it.next();
assertTrue(cidlist.remove(a.getId()));
it.remove();
}
assertEquals(0,cidlist.size());
assertEquals(0,msg.getAttachments().size());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testCXF3582c() throws Exception {
String contentType="multipart/related; type=\"application/xop+xml\"; " + "boundary=\"uuid:906fa67b-85f9-4ef5-8e3d-52416022d463\"; " + "start=\"\"; start-info=\"text/xml\"";
Message message=new MessageImpl();
message.put(Message.CONTENT_TYPE,contentType);
message.setContent(InputStream.class,getClass().getResourceAsStream("cxf3582.data"));
message.put(AttachmentDeserializer.ATTACHMENT_DIRECTORY,System.getProperty("java.io.tmpdir"));
message.put(AttachmentDeserializer.ATTACHMENT_MEMORY_THRESHOLD,String.valueOf(AttachmentDeserializer.THRESHOLD));
AttachmentDeserializer ad=new AttachmentDeserializer(message,Collections.singletonList("multipart/related"));
ad.initializeAttachments();
String cid="1a66bb35-67fc-4e89-9f33-48af417bf9fe-1@apache.org";
DataSource ds=AttachmentUtil.getAttachmentDataSource(cid,message.getAttachments());
byte bts[]=new byte[1024];
InputStream ins=ds.getInputStream();
int count=0;
int x=ins.read(bts,100,600);
while (x != -1) {
count+=x;
x=ins.read(bts,100,600);
}
assertEquals(500,count);
assertEquals(-1,ins.read(new byte[1000],100,600));
cid="1a66bb35-67fc-4e89-9f33-48af417bf9fe-2@apache.org";
ds=AttachmentUtil.getAttachmentDataSource(cid,message.getAttachments());
bts=new byte[1024];
ins=ds.getInputStream();
count=0;
x=ins.read(bts,100,600);
while (x != -1) {
count+=x;
x=ins.read(bts,100,600);
}
assertEquals(1249,count);
assertEquals(-1,ins.read(new byte[1000],100,600));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testDeserializerSwA() throws Exception {
InputStream is=getClass().getResourceAsStream("swadata");
String ct="multipart/related; type=\"text/xml\"; " + "start=\"<86048FF3556694F7DA1918466DDF8143>\"; " + "boundary=\"----=_Part_0_14158819.1167275505862\"";
msg.put(Message.CONTENT_TYPE,ct);
msg.setContent(InputStream.class,is);
AttachmentDeserializer deserializer=new AttachmentDeserializer(msg);
deserializer.initializeAttachments();
InputStream attBody=msg.getContent(InputStream.class);
assertTrue(attBody != is);
assertTrue(attBody instanceof DelegatingInputStream);
Collection atts=msg.getAttachments();
assertNotNull(atts);
Iterator itr=atts.iterator();
assertTrue(itr.hasNext());
Attachment a=itr.next();
assertNotNull(a);
InputStream attIs=a.getDataHandler().getInputStream();
ByteArrayOutputStream out=new ByteArrayOutputStream();
IOUtils.copy(attBody,out);
assertTrue(out.toString().startsWith("
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testCXF3582b() throws Exception {
String contentType="multipart/related; type=\"application/xop+xml\"; " + "boundary=\"uuid:906fa67b-85f9-4ef5-8e3d-52416022d463\"; " + "start=\"\"; start-info=\"text/xml\"";
Message message=new MessageImpl();
message.put(Message.CONTENT_TYPE,contentType);
message.setContent(InputStream.class,getClass().getResourceAsStream("cxf3582.data"));
message.put(AttachmentDeserializer.ATTACHMENT_DIRECTORY,System.getProperty("java.io.tmpdir"));
message.put(AttachmentDeserializer.ATTACHMENT_MEMORY_THRESHOLD,String.valueOf(AttachmentDeserializer.THRESHOLD));
AttachmentDeserializer ad=new AttachmentDeserializer(message,Collections.singletonList("multipart/related"));
ad.initializeAttachments();
String cid="1a66bb35-67fc-4e89-9f33-48af417bf9fe-1@apache.org";
DataSource ds=AttachmentUtil.getAttachmentDataSource(cid,message.getAttachments());
byte bts[]=new byte[1024];
InputStream ins=ds.getInputStream();
int count=0;
int x=ins.read(bts,500,200);
while (x != -1) {
count+=x;
x=ins.read(bts,500,200);
}
assertEquals(500,count);
assertEquals(-1,ins.read(new byte[1000],500,500));
cid="1a66bb35-67fc-4e89-9f33-48af417bf9fe-2@apache.org";
ds=AttachmentUtil.getAttachmentDataSource(cid,message.getAttachments());
bts=new byte[1024];
ins=ds.getInputStream();
count=0;
x=ins.read(bts,500,200);
while (x != -1) {
count+=x;
x=ins.read(bts,500,200);
}
assertEquals(1249,count);
assertEquals(-1,ins.read(new byte[1000],500,500));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testDeserializerMtomWithAxis2StyleBoundaries() throws Exception {
InputStream is=getClass().getResourceAsStream("axis2_mimedata");
String ct="multipart/related; type=\"application/xop+xml\"; " + "start=\"\"; " + "start-info=\"text/xml; charset=utf-8\"; "+ "boundary=MIMEBoundaryurn_uuid_6BC4984D5D38EB283C1177616488109";
msg.put(Message.CONTENT_TYPE,ct);
msg.setContent(InputStream.class,is);
AttachmentDeserializer deserializer=new AttachmentDeserializer(msg);
deserializer.initializeAttachments();
InputStream attBody=msg.getContent(InputStream.class);
assertTrue(attBody != is);
assertTrue(attBody instanceof DelegatingInputStream);
Collection atts=msg.getAttachments();
assertNotNull(atts);
Iterator itr=atts.iterator();
assertTrue(itr.hasNext());
Attachment a=itr.next();
assertNotNull(a);
InputStream attIs=a.getDataHandler().getInputStream();
ByteArrayOutputStream out=new ByteArrayOutputStream();
IOUtils.copy(attBody,out);
assertTrue(out.toString().startsWith("
InternalCallVerifier EqualityVerifier
@Test public void testSmallStream() throws Exception {
byte[] messageBytes=("------=_Part_1\n\nJJJJ\n------=_Part_1\n\n" + "Content-Transfer-Encoding: binary\n\n=3D=3D=3D\n------=_Part_1\n").getBytes();
PushbackInputStream pushbackStream=new PushbackInputStream(new ByteArrayInputStream(messageBytes),2048);
pushbackStream.read(new byte[4096],0,4015);
pushbackStream.unread(messageBytes);
pushbackStream.read(new byte[72]);
MimeBodyPartInputStream m=new MimeBodyPartInputStream(pushbackStream,"------=_Part_1".getBytes(),2048);
assertEquals(10,m.read(new byte[1000]));
assertEquals(-1,m.read(new byte[1000]));
assertEquals(-1,m.read(new byte[1000]));
m.close();
}
APIUtilityVerifier IterativeVerifier BooleanVerifier InternalCallVerifier EqualityVerifier PublicFieldVerifier HybridVerifier
@Test public void testCXF3383() throws Exception {
String contentType="multipart/related; type=\"application/xop+xml\";" + " boundary=\"uuid:7a555f51-c9bb-4bd4-9929-706899e2f793\"; start=" + "\"\"; start-info=\"text/xml\"";
Message message=new MessageImpl();
message.put(Message.CONTENT_TYPE,contentType);
message.setContent(InputStream.class,getClass().getResourceAsStream("cxf3383.data"));
message.put(AttachmentDeserializer.ATTACHMENT_DIRECTORY,System.getProperty("java.io.tmpdir"));
message.put(AttachmentDeserializer.ATTACHMENT_MEMORY_THRESHOLD,String.valueOf(AttachmentDeserializer.THRESHOLD));
AttachmentDeserializer ad=new AttachmentDeserializer(message,Collections.singletonList("multipart/related"));
ad.initializeAttachments();
for (int x=1; x < 50; x++) {
String cid="1882f79d-e20a-4b36-a222-7a75518cf395-" + x + "@cxf.apache.org";
DataSource ds=AttachmentUtil.getAttachmentDataSource(cid,message.getAttachments());
byte bts[]=new byte[1024];
InputStream ins=ds.getInputStream();
int count=0;
int sz=ins.read(bts,0,bts.length);
while (sz != -1) {
count+=sz;
assertTrue(count < bts.length);
sz=ins.read(bts,count,bts.length - count);
}
assertEquals(x + 1,count);
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier PublicFieldVerifier
@Test public void testCXF3582() throws Exception {
String contentType="multipart/related; type=\"application/xop+xml\"; " + "boundary=\"uuid:906fa67b-85f9-4ef5-8e3d-52416022d463\"; " + "start=\"\"; start-info=\"text/xml\"";
Message message=new MessageImpl();
message.put(Message.CONTENT_TYPE,contentType);
message.setContent(InputStream.class,getClass().getResourceAsStream("cxf3582.data"));
message.put(AttachmentDeserializer.ATTACHMENT_DIRECTORY,System.getProperty("java.io.tmpdir"));
message.put(AttachmentDeserializer.ATTACHMENT_MEMORY_THRESHOLD,String.valueOf(AttachmentDeserializer.THRESHOLD));
AttachmentDeserializer ad=new AttachmentDeserializer(message,Collections.singletonList("multipart/related"));
ad.initializeAttachments();
String cid="1a66bb35-67fc-4e89-9f33-48af417bf9fe-1@apache.org";
DataSource ds=AttachmentUtil.getAttachmentDataSource(cid,message.getAttachments());
byte bts[]=new byte[1024];
InputStream ins=ds.getInputStream();
int count=ins.read(bts,0,bts.length);
assertEquals(500,count);
assertEquals(-1,ins.read(new byte[1000],500,500));
cid="1a66bb35-67fc-4e89-9f33-48af417bf9fe-2@apache.org";
ds=AttachmentUtil.getAttachmentDataSource(cid,message.getAttachments());
bts=new byte[1024];
ins=ds.getInputStream();
count=ins.read(bts,0,bts.length);
assertEquals(1024,count);
assertEquals(225,ins.read(new byte[1000],500,500));
assertEquals(-1,ins.read(new byte[1000],500,500));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testDeserializerMtom() throws Exception {
InputStream is=getClass().getResourceAsStream("mimedata");
String ct="multipart/related; type=\"application/xop+xml\"; " + "start=\"\"; " + "start-info=\"text/xml; charset=utf-8\"; "+ "boundary=\"----=_Part_4_701508.1145579811786\"";
msg.put(Message.CONTENT_TYPE,ct);
msg.setContent(InputStream.class,is);
AttachmentDeserializer deserializer=new AttachmentDeserializer(msg);
deserializer.initializeAttachments();
InputStream attBody=msg.getContent(InputStream.class);
assertTrue(attBody != is);
assertTrue(attBody instanceof DelegatingInputStream);
Collection atts=msg.getAttachments();
assertNotNull(atts);
Iterator itr=atts.iterator();
assertTrue(itr.hasNext());
Attachment a=itr.next();
assertNotNull(a);
InputStream attIs=a.getDataHandler().getInputStream();
ByteArrayOutputStream out=new ByteArrayOutputStream();
IOUtils.copy(attBody,out);
assertTrue(out.toString().startsWith("
APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testDeserializerSwAWithoutBoundryInContentType() throws Exception {
InputStream is=getClass().getResourceAsStream("swadata");
String ct="multipart/related; type=\"text/xml\"; ";
msg.put(Message.CONTENT_TYPE,ct);
msg.setContent(InputStream.class,is);
AttachmentDeserializer deserializer=new AttachmentDeserializer(msg);
deserializer.initializeAttachments();
InputStream attBody=msg.getContent(InputStream.class);
assertTrue(attBody != is);
assertTrue(attBody instanceof DelegatingInputStream);
Collection atts=msg.getAttachments();
assertNotNull(atts);
Iterator itr=atts.iterator();
assertTrue(itr.hasNext());
Attachment a=itr.next();
assertNotNull(a);
InputStream attIs=a.getDataHandler().getInputStream();
ByteArrayOutputStream out=new ByteArrayOutputStream();
IOUtils.copy(attBody,out);
assertTrue(out.toString().startsWith("
InternalCallVerifier EqualityVerifier
@Test public void testDoesntReturnZero() throws Exception {
String contentType="multipart/mixed;boundary=----=_Part_1";
byte[] messageBytes=("------=_Part_1\n\n" + "JJJJ\n" + "------=_Part_1"+ "\n\nContent-Transfer-Encoding: binary\n\n"+ "ABCD1\r\n"+ "------=_Part_1"+ "\n\nContent-Transfer-Encoding: binary\n\n"+ "ABCD2\r\n"+ "------=_Part_1"+ "\n\nContent-Transfer-Encoding: binary\n\n"+ "ABCD3\r\n"+ "------=_Part_1--").getBytes(StandardCharsets.UTF_8);
ByteArrayInputStream in=new ByteArrayInputStream(messageBytes){
public int read( byte[] b, int off, int len){
return super.read(b,off,len >= 2 ? 2 : len);
}
}
;
Message message=new MessageImpl();
message.put(Message.CONTENT_TYPE,contentType);
message.setContent(InputStream.class,in);
message.put(AttachmentDeserializer.ATTACHMENT_DIRECTORY,System.getProperty("java.io.tmpdir"));
message.put(AttachmentDeserializer.ATTACHMENT_MEMORY_THRESHOLD,String.valueOf(AttachmentDeserializer.THRESHOLD));
AttachmentDeserializer ad=new AttachmentDeserializer(message,Collections.singletonList("multipart/mixed"));
ad.initializeAttachments();
String s=getString(message.getContent(InputStream.class));
assertEquals("JJJJ",s.trim());
int count=1;
for ( Attachment a : message.getAttachments()) {
s=getString(a.getDataHandler().getInputStream());
assertEquals("ABCD" + count++,s);
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testNoBoundaryInCT() throws Exception {
String message="SomeHeader: foo\n" + "------=_Part_34950_1098328613.1263781527359\n" + "Content-Type: text/xml; charset=UTF-8\n"+ "Content-Transfer-Encoding: binary\n"+ "Content-Id: <318731183421.1263781527359.IBM.WEBSERVICES@auhpap02>\n"+ "\n"+ " \n"+ "------=_Part_34950_1098328613.1263781527359\n"+ "Content-Type: text/xml\n"+ "Content-Transfer-Encoding: binary\n"+ "Content-Id: \n"+ "\n"+ "\n"+ "------=_Part_34950_1098328613.1263781527359--";
Matcher m=Pattern.compile("^--(\\S*)$").matcher(message);
Assert.assertFalse(m.find());
m=Pattern.compile("^--(\\S*)$",Pattern.MULTILINE).matcher(message);
Assert.assertTrue(m.find());
msg=new MessageImpl();
msg.setContent(InputStream.class,new ByteArrayInputStream(message.getBytes(StandardCharsets.UTF_8)));
msg.put(Message.CONTENT_TYPE,"multipart/related");
AttachmentDeserializer ad=new AttachmentDeserializer(msg);
ad.initializeAttachments();
assertEquals(1,msg.getAttachments().size());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testDeserializerWithCachedFile() throws Exception {
InputStream is=getClass().getResourceAsStream("mimedata");
String ct="multipart/related; type=\"application/xop+xml\"; " + "start=\"\"; " + "start-info=\"text/xml; charset=utf-8\"; "+ "boundary=\"----=_Part_4_701508.1145579811786\"";
msg.put(Message.CONTENT_TYPE,ct);
msg.setContent(InputStream.class,is);
msg.put(AttachmentDeserializer.ATTACHMENT_MEMORY_THRESHOLD,"10");
AttachmentDeserializer deserializer=new AttachmentDeserializer(msg);
deserializer.initializeAttachments();
InputStream attBody=msg.getContent(InputStream.class);
assertTrue(attBody != is);
assertTrue(attBody instanceof DelegatingInputStream);
Collection atts=msg.getAttachments();
assertNotNull(atts);
Iterator itr=atts.iterator();
assertTrue(itr.hasNext());
Attachment a=itr.next();
assertNotNull(a);
InputStream attIs=a.getDataHandler().getInputStream();
assertFalse(itr.hasNext());
ByteArrayOutputStream out=new ByteArrayOutputStream();
IOUtils.copy(attIs,out);
assertTrue(out.size() > 1000);
}
Class: org.apache.cxf.attachment.AttachmentSerializerTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testMessageMTOM() throws Exception {
MessageImpl msg=new MessageImpl();
Collection atts=new ArrayList();
AttachmentImpl a=new AttachmentImpl("test.xml");
InputStream is=getClass().getResourceAsStream("my.wav");
ByteArrayDataSource ds=new ByteArrayDataSource(is,"application/octet-stream");
a.setDataHandler(new DataHandler(ds));
atts.add(a);
msg.setAttachments(atts);
msg.put(Message.CONTENT_TYPE,"application/soap+xml");
ByteArrayOutputStream out=new ByteArrayOutputStream();
msg.setContent(OutputStream.class,out);
AttachmentSerializer serializer=new AttachmentSerializer(msg);
serializer.writeProlog();
String ct=(String)msg.get(Message.CONTENT_TYPE);
assertTrue(ct.indexOf("multipart/related;") == 0);
assertTrue(ct.indexOf("start=\"\"") > -1);
assertTrue(ct.indexOf("start-info=\"application/soap+xml\"") > -1);
out.write(" ".getBytes());
serializer.writeAttachments();
out.flush();
DataSource source=new ByteArrayDataSource(new ByteArrayInputStream(out.toByteArray()),ct);
MimeMultipart mpart=new MimeMultipart(source);
Session session=Session.getDefaultInstance(new Properties());
MimeMessage inMsg=new MimeMessage(session);
inMsg.setContent(mpart);
inMsg.addHeaderLine("Content-Type: " + ct);
MimeMultipart multipart=(MimeMultipart)inMsg.getContent();
MimeBodyPart part=(MimeBodyPart)multipart.getBodyPart(0);
assertEquals("application/xop+xml; charset=UTF-8; type=\"application/soap+xml\"",part.getHeader("Content-Type")[0]);
assertEquals("binary",part.getHeader("Content-Transfer-Encoding")[0]);
assertEquals("",part.getHeader("Content-ID")[0]);
InputStream in=part.getDataHandler().getInputStream();
ByteArrayOutputStream bodyOut=new ByteArrayOutputStream();
IOUtils.copy(in,bodyOut);
out.close();
in.close();
assertEquals(" ",bodyOut.toString());
MimeBodyPart part2=(MimeBodyPart)multipart.getBodyPart(1);
assertEquals("application/octet-stream",part2.getHeader("Content-Type")[0]);
assertEquals("binary",part2.getHeader("Content-Transfer-Encoding")[0]);
assertEquals("",part2.getHeader("Content-ID")[0]);
}
Class: org.apache.cxf.binding.coloc.ColocMessageObserverTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testObserverOnMessage() throws Exception {
msg.setExchange(ex);
Binding binding=control.createMock(Binding.class);
EasyMock.expect(ep.getBinding()).andReturn(binding);
Message inMsg=new MessageImpl();
EasyMock.expect(binding.createMessage()).andReturn(inMsg);
EasyMock.expect(ep.getService()).andReturn(srv).anyTimes();
EasyMock.expect(bus.getExtension(PhaseManager.class)).andReturn(new PhaseManagerImpl()).times(2);
EasyMock.expect(bus.getInInterceptors()).andReturn(new ArrayList>());
EasyMock.expect(ep.getInInterceptors()).andReturn(new ArrayList>());
EasyMock.expect(srv.getInInterceptors()).andReturn(new ArrayList>());
EasyMock.expect(bus.getExtension(ClassLoader.class)).andReturn(this.getClass().getClassLoader());
control.replay();
observer=new TestColocMessageObserver(ep,bus);
observer.onMessage(msg);
control.verify();
Exchange inEx=inMsg.getExchange();
assertNotNull("Should Have a valid Exchange",inEx);
assertEquals("Message.REQUESTOR_ROLE should be false",Boolean.FALSE,inMsg.get(Message.REQUESTOR_ROLE));
assertEquals("Message.INBOUND_MESSAGE should be true",Boolean.TRUE,inMsg.get(Message.INBOUND_MESSAGE));
assertNotNull("Chain should be set",inMsg.getInterceptorChain());
Exchange ex1=msg.getExchange();
assertNotNull("Exchange should be set",ex1);
}
InternalCallVerifier NullVerifier
@Test public void testSetExchangeProperties() throws Exception {
QName opName=new QName("A","B");
msg.put(Message.WSDL_OPERATION,opName);
EasyMock.expect(ep.getService()).andReturn(srv);
Binding binding=control.createMock(Binding.class);
EasyMock.expect(ep.getBinding()).andReturn(binding);
EndpointInfo ei=control.createMock(EndpointInfo.class);
EasyMock.expect(ep.getEndpointInfo()).andReturn(ei);
BindingInfo bi=control.createMock(BindingInfo.class);
EasyMock.expect(ei.getBinding()).andReturn(bi);
BindingOperationInfo boi=control.createMock(BindingOperationInfo.class);
EasyMock.expect(bi.getOperation(opName)).andReturn(boi);
EasyMock.expect(bus.getExtension(ClassLoader.class)).andReturn(this.getClass().getClassLoader());
control.replay();
observer=new ColocMessageObserver(ep,bus);
observer.setExchangeProperties(ex,msg);
control.verify();
assertNotNull("Bus should be set",ex.getBus());
assertNotNull("Endpoint should be set",ex.getEndpoint());
assertNotNull("Binding should be set",ex.getBinding());
assertNotNull("Service should be set",ex.getService());
assertNotNull("BindingOperationInfo should be set",ex.getBindingOperationInfo());
}
Class: org.apache.cxf.binding.coloc.ColocOutInterceptorTest InternalCallVerifier IdentityVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testInvokeInboundChain(){
msg.setExchange(null);
Bus bus=setupBus();
colocOut.setBus(bus);
PhaseManager pm=new PhaseManagerImpl();
EasyMock.expect(bus.getExtension(PhaseManager.class)).andReturn(pm).times(2);
Endpoint ep=control.createMock(Endpoint.class);
Binding bd=control.createMock(Binding.class);
Service srv=control.createMock(Service.class);
ex.setInMessage(msg);
ex.put(Bus.class,bus);
ex.put(Endpoint.class,ep);
ex.put(Service.class,srv);
EasyMock.expect(ep.getBinding()).andReturn(bd);
EasyMock.expect(bd.createMessage()).andReturn(new MessageImpl());
EasyMock.expect(ep.getInInterceptors()).andReturn(new ArrayList>()).atLeastOnce();
EasyMock.expect(ep.getService()).andReturn(srv).atLeastOnce();
EasyMock.expect(srv.getInInterceptors()).andReturn(new ArrayList>()).atLeastOnce();
EasyMock.expect(bus.getInInterceptors()).andReturn(new ArrayList>()).atLeastOnce();
control.replay();
colocOut.invokeInboundChain(ex,ep);
Message inMsg=ex.getInMessage();
assertNotSame(msg,inMsg);
assertEquals("Requestor role should be set to true.",Boolean.TRUE,inMsg.get(Message.REQUESTOR_ROLE));
assertEquals("Inbound Message should be set to true.",Boolean.TRUE,inMsg.get(Message.INBOUND_MESSAGE));
assertNotNull("Inbound Message should have interceptor chain set.",inMsg.getInterceptorChain());
assertEquals("Client Invoke state should be FINISHED",Boolean.TRUE,ex.get(ClientImpl.FINISHED));
control.verify();
}
InternalCallVerifier EqualityVerifier
@Test public void testColocOutIsColocatedPropertySet() throws Exception {
colocOut=new TestColocOutInterceptor1();
Bus bus=setupBus();
ServerRegistry sr=control.createMock(ServerRegistry.class);
EasyMock.expect(bus.getExtension(ServerRegistry.class)).andReturn(sr);
Server s1=control.createMock(Server.class);
List list=new ArrayList();
list.add(s1);
Endpoint sep=control.createMock(Endpoint.class);
ex.put(Endpoint.class,sep);
QName op=new QName("E","F");
QName intf=new QName("G","H");
BindingInfo sbi=control.createMock(BindingInfo.class);
ServiceInfo ssi=new ServiceInfo();
InterfaceInfo sii=new InterfaceInfo(ssi,intf);
sii.addOperation(op);
OperationInfo soi=sii.getOperation(op);
ServiceInfo rsi=new ServiceInfo();
InterfaceInfo rii=new InterfaceInfo(rsi,intf);
rii.addOperation(op);
OperationInfo roi=rii.getOperation(op);
BindingOperationInfo sboi=control.createMock(BindingOperationInfo.class);
BindingOperationInfo rboi=control.createMock(BindingOperationInfo.class);
ex.put(BindingOperationInfo.class,sboi);
Service ses=control.createMock(Service.class);
EndpointInfo sei=control.createMock(EndpointInfo.class);
Endpoint rep=control.createMock(Endpoint.class);
Service res=control.createMock(Service.class);
BindingInfo rbi=control.createMock(BindingInfo.class);
EndpointInfo rei=control.createMock(EndpointInfo.class);
EasyMock.expect(sr.getServers()).andReturn(list);
EasyMock.expect(sep.getService()).andReturn(ses);
EasyMock.expect(sep.getEndpointInfo()).andReturn(sei);
EasyMock.expect(s1.getEndpoint()).andReturn(rep);
EasyMock.expect(rep.getService()).andReturn(res);
EasyMock.expect(rep.getEndpointInfo()).andReturn(rei);
EasyMock.expect(ses.getName()).andReturn(new QName("A","B"));
EasyMock.expect(res.getName()).andReturn(new QName("A","B"));
EasyMock.expect(rei.getName()).andReturn(new QName("C","D"));
EasyMock.expect(sei.getName()).andReturn(new QName("C","D"));
EasyMock.expect(rei.getBinding()).andReturn(rbi);
EasyMock.expect(sboi.getName()).andReturn(op).anyTimes();
EasyMock.expect(sboi.getOperationInfo()).andReturn(soi);
EasyMock.expect(rboi.getName()).andReturn(op).anyTimes();
EasyMock.expect(rboi.getOperationInfo()).andReturn(roi);
EasyMock.expect(rbi.getOperation(op)).andReturn(rboi);
InterceptorChain chain=control.createMock(InterceptorChain.class);
msg.setInterceptorChain(chain);
EasyMock.expect(sboi.getBinding()).andReturn(sbi);
EasyMock.expect(sbi.getInterface()).andReturn(sii);
control.replay();
colocOut.handleMessage(msg);
assertEquals("COLOCATED property should be set",Boolean.TRUE,msg.get(COLOCATED));
assertEquals("Message.WSDL_OPERATION property should be set",op,msg.get(Message.WSDL_OPERATION));
assertEquals("Message.WSDL_INTERFACE property should be set",intf,msg.get(Message.WSDL_INTERFACE));
control.verify();
}
Class: org.apache.cxf.binding.coloc.ColocUtilTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testIsSameMessageInfo(){
OperationInfo oi=control.createMock(OperationInfo.class);
boolean match=ColocUtil.isSameMessageInfo(null,null);
assertEquals("Should return true",true,match);
QName mn1=new QName("A","B");
QName mn2=new QName("C","D");
MessageInfo mi1=new MessageInfo(oi,MessageInfo.Type.INPUT,mn1);
MessageInfo mi2=new MessageInfo(oi,MessageInfo.Type.INPUT,mn2);
match=ColocUtil.isSameMessageInfo(mi1,null);
assertEquals("Should not find a match",false,match);
match=ColocUtil.isSameMessageInfo(null,mi2);
assertEquals("Should not find a match",false,match);
MessagePartInfo mpi=new MessagePartInfo(new QName("","B"),null);
mpi.setTypeClass(InHeaderT.class);
mi1.addMessagePart(mpi);
mpi=new MessagePartInfo(new QName("","D"),null);
mpi.setTypeClass(OutHeaderT.class);
mi2.addMessagePart(mpi);
match=ColocUtil.isSameMessageInfo(mi1,mi2);
assertEquals("Should not find a match",false,match);
mpi.setTypeClass(InHeaderT.class);
match=ColocUtil.isSameMessageInfo(mi1,mi2);
assertEquals("Should find a match",true,match);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetOutInterceptorChain() throws Exception {
PhaseManagerImpl phaseMgr=new PhaseManagerImpl();
SortedSet list=phaseMgr.getInPhases();
ColocUtil.setPhases(list,Phase.SETUP,Phase.POST_LOGICAL);
Endpoint ep=control.createMock(Endpoint.class);
Service srv=control.createMock(Service.class);
Exchange ex=new ExchangeImpl();
ex.put(Bus.class,bus);
ex.put(Endpoint.class,ep);
ex.put(Service.class,srv);
EasyMock.expect(ep.getOutInterceptors()).andReturn(new ArrayList>()).atLeastOnce();
EasyMock.expect(ep.getService()).andReturn(srv).atLeastOnce();
EasyMock.expect(srv.getOutInterceptors()).andReturn(new ArrayList>()).atLeastOnce();
EasyMock.expect(bus.getOutInterceptors()).andReturn(new ArrayList>()).atLeastOnce();
control.replay();
InterceptorChain chain=ColocUtil.getOutInterceptorChain(ex,list);
control.verify();
assertNotNull("Should have chain instance",chain);
Iterator> iter=chain.iterator();
assertEquals("Should not have interceptors in chain",false,iter.hasNext());
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testSetColocOutPhases() throws Exception {
PhaseManagerImpl phaseMgr=new PhaseManagerImpl();
SortedSet list=phaseMgr.getOutPhases();
int size1=list.size();
ColocUtil.setPhases(list,Phase.SETUP,Phase.POST_LOGICAL);
assertNotSame("The list size should not be same",size1,list.size());
assertEquals("Expecting Phase.SETUP",list.first().getName(),Phase.SETUP);
assertEquals("Expecting Phase.POST_LOGICAL",list.last().getName(),Phase.POST_LOGICAL);
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testSetColocInPhases() throws Exception {
PhaseManagerImpl phaseMgr=new PhaseManagerImpl();
SortedSet list=phaseMgr.getInPhases();
int size1=list.size();
ColocUtil.setPhases(list,Phase.USER_LOGICAL,Phase.INVOKE);
assertNotSame("The list size should not be same",size1,list.size());
assertEquals("Expecting Phase.USER_LOGICAL",list.first().getName(),Phase.USER_LOGICAL);
assertEquals("Expecting Phase.POST_INVOKE",list.last().getName(),Phase.INVOKE);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetInInterceptorChain() throws Exception {
PhaseManagerImpl phaseMgr=new PhaseManagerImpl();
SortedSet list=phaseMgr.getInPhases();
ColocUtil.setPhases(list,Phase.SETUP,Phase.POST_LOGICAL);
Endpoint ep=control.createMock(Endpoint.class);
Service srv=control.createMock(Service.class);
Exchange ex=new ExchangeImpl();
ex.put(Bus.class,bus);
ex.put(Endpoint.class,ep);
ex.put(Service.class,srv);
EasyMock.expect(bus.getExtension(PhaseManager.class)).andReturn(phaseMgr);
EasyMock.expect(ep.getInInterceptors()).andReturn(new ArrayList>()).atLeastOnce();
EasyMock.expect(ep.getService()).andReturn(srv).atLeastOnce();
EasyMock.expect(srv.getInInterceptors()).andReturn(new ArrayList>()).atLeastOnce();
EasyMock.expect(bus.getInInterceptors()).andReturn(new ArrayList>()).atLeastOnce();
control.replay();
InterceptorChain chain=ColocUtil.getInInterceptorChain(ex,list);
control.verify();
assertNotNull("Should have chain instance",chain);
Iterator> iter=chain.iterator();
assertEquals("Should not have interceptors in chain",false,iter.hasNext());
assertNotNull("OutFaultObserver should be set",chain.getFaultObserver());
}
Class: org.apache.cxf.binding.corba.CorbaBindingFactoryTest BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCreateBinding() throws Exception {
IMocksControl control=EasyMock.createNiceControl();
BindingInfo bindingInfo=control.createMock(BindingInfo.class);
CorbaBinding binding=(CorbaBinding)factory.createBinding(bindingInfo);
assertNotNull(binding);
assertTrue(CorbaBinding.class.isInstance(binding));
List> inInterceptors=binding.getInInterceptors();
assertNotNull(inInterceptors);
List> outInterceptors=binding.getOutInterceptors();
assertNotNull(outInterceptors);
assertEquals(2,inInterceptors.size());
assertEquals(2,outInterceptors.size());
}
InternalCallVerifier NullVerifier
@Test public void testGetUriPrefixes() throws Exception {
Set prefixes=factory.getUriPrefixes();
assertNotNull("Prefixes should not be null",prefixes != null);
}
InternalCallVerifier NullVerifier
@Test public void testGetCorbaConduit() throws Exception {
setupServiceInfo("http://cxf.apache.org/bindings/corba/simple","/wsdl_corbabinding/simpleIdl.wsdl","SimpleCORBAService","SimpleCORBAPort");
Conduit conduit=factory.getConduit(endpointInfo,bus);
assertNotNull(conduit);
conduit=factory.getConduit(endpointInfo,null,bus);
assertNotNull(conduit);
target=EasyMock.createMock(EndpointReferenceType.class);
conduit=factory.getConduit(endpointInfo,target,bus);
assertNotNull(conduit);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testTransportIds() throws Exception {
setupServiceInfo("http://cxf.apache.org/bindings/corba/simple","/wsdl_corbabinding/simpleIdl.wsdl","SimpleCORBAService","SimpleCORBAPort");
List strs=new ArrayList();
strs.add("one");
strs.add("two");
factory.setTransportIds(strs);
List retStrs=factory.getTransportIds();
assertNotNull(retStrs);
String str=retStrs.get(0);
assertEquals("one",str.toString());
str=retStrs.get(1);
assertEquals("two",str.toString());
}
InternalCallVerifier NullVerifier
@Test public void testGetDestination() throws Exception {
setupServiceInfo("http://cxf.apache.org/bindings/corba/simple","/wsdl_corbabinding/simpleIdl.wsdl","SimpleCORBAService","SimpleCORBAPort");
Destination destination=factory.getDestination(endpointInfo,bus);
assertNotNull(destination);
target=destination.getAddress();
assertNotNull(target);
}
Class: org.apache.cxf.binding.corba.CorbaBindingTest InternalCallVerifier NullVerifier
@Test public void testCorbaBinding(){
CorbaBinding binding=new CorbaBinding();
List> in=binding.getInInterceptors();
assertNotNull(in);
List> out=binding.getOutInterceptors();
assertNotNull(out);
List> infault=binding.getInFaultInterceptors();
assertNotNull(infault);
List> outfault=binding.getFaultOutInterceptors();
assertNotNull(outfault);
Message message=binding.createMessage();
message.put(ORB.class,orb);
assertNotNull(message);
ORB corbaORB=message.get(ORB.class);
assertNotNull(corbaORB);
MessageImpl mesage=new MessageImpl();
mesage.put(ORB.class,orb);
Message msg=binding.createMessage(mesage);
assertNotNull(msg);
ORB corbaOrb=msg.get(ORB.class);
assertNotNull(corbaOrb);
}
Class: org.apache.cxf.binding.corba.CorbaConduitTest BooleanVerifier InternalCallVerifier
@Test public void testGetTarget() throws Exception {
CorbaConduit conduit=setupCorbaConduit(false);
EndpointReferenceType endpoint=conduit.getTarget();
assertTrue("EndpointReferenceType should not be null",endpoint != null);
}
InternalCallVerifier EqualityVerifier
@Test public void testGetOperationExceptions(){
CorbaConduit conduit=control.createMock(CorbaConduit.class);
OperationType opType=control.createMock(OperationType.class);
CorbaTypeMap typeMap=control.createMock(CorbaTypeMap.class);
List exlist=CastUtils.cast(control.createMock(ArrayList.class));
opType.getRaises();
EasyMock.expectLastCall().andReturn(exlist);
int i=0;
EasyMock.expect(exlist.size()).andReturn(i);
RaisesType rType=control.createMock(RaisesType.class);
EasyMock.expect(exlist.get(0)).andReturn(rType);
control.replay();
conduit.getOperationExceptions(opType,typeMap);
assertEquals(exlist.size(),0);
}
BooleanVerifier InternalCallVerifier
@Test public void testPrepare() throws Exception {
setupServiceInfo("http://cxf.apache.org/bindings/corba/simple","/wsdl_corbabinding/simpleIdl.wsdl","SimpleCORBAService","SimpleCORBAPort");
CorbaDestination destination=new CorbaDestination(endpointInfo,orbConfig);
if (System.getProperty("java.vendor").contains("IBM")) {
destination.activate();
}
CorbaConduit conduit=new CorbaConduit(endpointInfo,destination.getAddress(),orbConfig);
CorbaMessage message=new CorbaMessage(new MessageImpl());
try {
conduit.prepare(message);
}
catch ( Exception ex) {
ex.printStackTrace();
}
OutputStream os=message.getContent(OutputStream.class);
assertTrue("OutputStream should not be null",os != null);
ORB orb2=(ORB)message.get("orb");
assertTrue("Orb should not be null",orb2 != null);
Object obj=message.get("endpoint");
assertTrue("EndpointReferenceType should not be null",obj != null);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBuildExceptionListEmpty() throws Exception {
CorbaConduit conduit=setupCorbaConduit(false);
Message msg=new MessageImpl();
CorbaMessage message=new CorbaMessage(msg);
OperationType opType=new OperationType();
opType.setName("review_data");
ExceptionList exList=conduit.getExceptionList(conduit.getOperationExceptions(opType,null),message,opType);
assertNotNull("ExcepitonList is not null",exList != null);
assertEquals("The list should be empty",exList.count(),0);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testGetAddress() throws Exception {
setupServiceInfo("http://cxf.apache.org/bindings/corba/simple","/wsdl_corbabinding/simpleIdl.wsdl","SimpleCORBAService","SimpleCORBAPort");
CorbaDestination destination=new CorbaDestination(endpointInfo,orbConfig);
endpointInfo.setAddress("corbaloc::localhost:40000/Simple");
CorbaConduit conduit=new CorbaConduit(endpointInfo,destination.getAddress(),orbConfig);
String address=conduit.getAddress();
assertTrue("address should not be null",address != null);
assertEquals(address,"corbaloc::localhost:40000/Simple");
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBuildArguments() throws Exception {
Message msg=new MessageImpl();
CorbaMessage message=new CorbaMessage(msg);
CorbaStreamable[] arguments=new CorbaStreamable[1];
QName objName=new QName("object");
QName objIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"short",CorbaConstants.NP_WSDL_CORBA);
TypeCode objTypeCode=orb.get_primitive_tc(TCKind.tk_short);
CorbaPrimitiveHandler obj1=new CorbaPrimitiveHandler(objName,objIdlType,objTypeCode,null);
CorbaStreamable arg=message.createStreamableObject(obj1,objName);
arguments[0]=arg;
arguments[0].setMode(org.omg.CORBA.ARG_OUT.value);
CorbaConduit conduit=setupCorbaConduit(false);
NVList list=conduit.getArguments(message);
assertNotNull("list should not be null",list != null);
message.setStreamableArguments(arguments);
NVList listArgs=conduit.getArguments(message);
assertNotNull("listArgs should not be null",listArgs != null);
assertNotNull("listArgs Item should not be null",listArgs.item(0) != null);
assertEquals("Name should be equal",listArgs.item(0).name(),"object");
assertEquals("flags should be 2",listArgs.item(0).flags(),2);
assertNotNull("Any Value should not be null",listArgs.item(0).value() != null);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBuildReturn() throws Exception {
Message msg=new MessageImpl();
CorbaMessage message=new CorbaMessage(msg);
QName objName=new QName("returnName");
QName objIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"short",CorbaConstants.NP_WSDL_CORBA);
TypeCode objTypeCode=orb.get_primitive_tc(TCKind.tk_short);
CorbaPrimitiveHandler obj1=new CorbaPrimitiveHandler(objName,objIdlType,objTypeCode,null);
CorbaStreamable arg=message.createStreamableObject(obj1,objName);
CorbaConduit conduit=setupCorbaConduit(false);
NamedValue ret=conduit.getReturn(message);
assertNotNull("Return should not be null",ret != null);
assertEquals("name should be equal",ret.name(),"return");
message.setStreamableReturn(arg);
NamedValue ret2=conduit.getReturn(message);
assertNotNull("Return2 should not be null",ret2 != null);
assertEquals("name should be equal",ret2.name(),"returnName");
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBuildExceptionListWithExceptions() throws Exception {
CorbaConduit conduit=setupCorbaConduit(false);
Message msg=new MessageImpl();
CorbaMessage message=new CorbaMessage(msg);
TestUtils testUtils=new TestUtils();
CorbaDestination destination=testUtils.getExceptionTypesTestDestination();
EndpointInfo endpointInfo2=destination.getEndPointInfo();
QName name=new QName("http://schemas.apache.org/idl/except","review_data","");
BindingOperationInfo bInfo=destination.getBindingInfo().getOperation(name);
OperationType opType=bInfo.getExtensor(OperationType.class);
CorbaTypeMap typeMap=null;
List corbaTypes=endpointInfo2.getService().getDescription().getExtensors(TypeMappingType.class);
if (corbaTypes != null) {
typeMap=CorbaUtils.createCorbaTypeMap(corbaTypes);
}
ExceptionList exList=conduit.getExceptionList(conduit.getOperationExceptions(opType,typeMap),message,opType);
assertNotNull("ExceptionList is not null",exList != null);
assertNotNull("TypeCode is not null",exList.item(0) != null);
assertEquals("ID should be equal",exList.item(0).id(),"IDL:BadRecord:1.0");
assertEquals("ID should be equal",exList.item(0).name(),"BadRecord");
assertEquals("ID should be equal",exList.item(0).member_count(),2);
assertEquals("ID should be equal",exList.item(0).member_name(0),"reason");
assertNotNull("Member type is not null",exList.item(0).member_type(0) != null);
}
BooleanVerifier InternalCallVerifier
@Test public void testGetTargetReference() throws Exception {
setupServiceInfo("http://cxf.apache.org/bindings/corba/simple","/wsdl_corbabinding/simpleIdl.wsdl","SimpleCORBAService","SimpleCORBAPort");
CorbaDestination destination=new CorbaDestination(endpointInfo,orbConfig);
CorbaConduit conduit=new CorbaConduit(endpointInfo,destination.getAddress(),orbConfig);
EndpointReferenceType t=null;
EndpointReferenceType ref=conduit.getTargetReference(t);
assertTrue("ref should not be null",ref != null);
}
Class: org.apache.cxf.binding.corba.CorbaDestinationTest BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testDestination() throws Exception {
endpointInfo=testUtils.setupServiceInfo("http://cxf.apache.org/bindings/corba/simple","/wsdl_corbabinding/simpleIdl.wsdl","SimpleCORBAService","SimpleCORBAPort");
CorbaDestination destination=new CorbaDestination(endpointInfo,orbConfig);
EndpointReferenceType rtype=destination.getAddress();
assertTrue("EndpointReferenceType should not be null",rtype != null);
BindingInfo bindingInfo=destination.getBindingInfo();
assertTrue("BindingInfo should not be null",bindingInfo != null);
EndpointInfo e2=destination.getEndPointInfo();
assertTrue("EndpointInfo should not be null",e2 != null);
Message m=new MessageImpl();
CorbaServerConduit serverConduit=(CorbaServerConduit)destination.getBackChannel(m);
assertNotNull("CorbaServerConduit should not be null",serverConduit);
}
Class: org.apache.cxf.binding.corba.CorbaMessageTest BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testGetCorbaMessageAttributes(){
CorbaMessage msg=new CorbaMessage(message);
QName param1Name=new QName("param1");
QName param1IdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"long",CorbaConstants.NP_WSDL_CORBA);
TypeCode param1TypeCode=orb.get_primitive_tc(TCKind.tk_long);
CorbaPrimitiveHandler param1=new CorbaPrimitiveHandler(param1Name,param1IdlType,param1TypeCode,null);
CorbaStreamable p1=msg.createStreamableObject(param1,param1Name);
QName param2Name=new QName("param2");
QName param2IdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"string",CorbaConstants.NP_WSDL_CORBA);
TypeCode param2TypeCode=orb.get_primitive_tc(TCKind.tk_string);
CorbaPrimitiveHandler param2=new CorbaPrimitiveHandler(param2Name,param2IdlType,param2TypeCode,null);
CorbaStreamable p2=msg.createStreamableObject(param2,param2Name);
msg.addStreamableArgument(p1);
msg.addStreamableArgument(p2);
CorbaStreamable[] arguments=msg.getStreamableArguments();
assertTrue(arguments.length == 2);
assertNotNull(arguments[0]);
assertNotNull(arguments[1]);
QName param3Name=new QName("param3");
QName param3IdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"short",CorbaConstants.NP_WSDL_CORBA);
TypeCode param3TypeCode=orb.get_primitive_tc(TCKind.tk_short);
CorbaPrimitiveHandler param3=new CorbaPrimitiveHandler(param3Name,param3IdlType,param3TypeCode,null);
CorbaStreamable p3=msg.createStreamableObject(param3,param3Name);
QName param4Name=new QName("param4");
QName param4IdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"float",CorbaConstants.NP_WSDL_CORBA);
TypeCode param4TypeCode=orb.get_primitive_tc(TCKind.tk_float);
CorbaPrimitiveHandler param4=new CorbaPrimitiveHandler(param4Name,param4IdlType,param4TypeCode,null);
CorbaStreamable p4=msg.createStreamableObject(param4,param4Name);
CorbaStreamable[] args=new CorbaStreamable[2];
args[0]=p3;
args[1]=p4;
msg.setStreamableArguments(args);
arguments=msg.getStreamableArguments();
assertTrue(arguments.length == 4);
assertNotNull(arguments[0]);
assertNotNull(arguments[1]);
assertNotNull(arguments[2]);
assertNotNull(arguments[3]);
NVList list=orb.create_list(2);
Any value=orb.create_any();
value.insert_Streamable(p1);
list.add_value(p1.getName(),value,p1.getMode());
value.insert_Streamable(p2);
list.add_value(p2.getName(),value,p2.getMode());
msg.setList(list);
NVList resultList=msg.getList();
assertTrue(resultList.count() == 2);
QName returnName=new QName("param2");
QName returnIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"boolean",CorbaConstants.NP_WSDL_CORBA);
TypeCode returnTypeCode=orb.get_primitive_tc(TCKind.tk_boolean);
CorbaPrimitiveHandler returnValue=new CorbaPrimitiveHandler(returnName,returnIdlType,returnTypeCode,null);
CorbaStreamable ret=msg.createStreamableObject(returnValue,returnName);
msg.setStreamableReturn(ret);
CorbaStreamable retVal=msg.getStreamableReturn();
assertNotNull(retVal);
}
Class: org.apache.cxf.binding.corba.CorbaServerConduitTest BooleanVerifier InternalCallVerifier
@Test public void testPrepare() throws Exception {
setupServiceInfo("http://cxf.apache.org/bindings/corba/simple","/wsdl_corbabinding/simpleIdl.wsdl","SimpleCORBAService","SimpleCORBAPort");
CorbaDestination destination=new CorbaDestination(endpointInfo,orbConfig);
CorbaServerConduit conduit=new CorbaServerConduit(endpointInfo,destination.getAddress(),targetObject,null,orbConfig,corbaTypeMap);
CorbaMessage message=new CorbaMessage(new MessageImpl());
try {
conduit.prepare(message);
}
catch ( Exception ex) {
ex.printStackTrace();
}
OutputStream os=message.getContent(OutputStream.class);
assertTrue("OutputStream should not be null",os != null);
ORB orb2=(ORB)message.get("orb");
assertTrue("Orb should not be null",orb2 != null);
Object obj=message.get("endpoint");
assertTrue("EndpointReferenceType should not be null",obj != null);
assertTrue("passed in targetObject is used",targetObject.equals(message.get(CorbaConstants.CORBA_ENDPOINT_OBJECT)));
destination.shutdown();
}
BooleanVerifier InternalCallVerifier
@Test public void testGetTargetReference() throws Exception {
setupServiceInfo("http://cxf.apache.org/bindings/corba/simple","/wsdl_corbabinding/simpleIdl.wsdl","SimpleCORBAService","SimpleCORBAPort");
CorbaDestination destination=new CorbaDestination(endpointInfo,orbConfig);
CorbaServerConduit conduit=new CorbaServerConduit(endpointInfo,destination.getAddress(),targetObject,null,orbConfig,corbaTypeMap);
EndpointReferenceType t=null;
EndpointReferenceType ref=conduit.getTargetReference(t);
assertTrue("ref should not be null",ref != null);
destination.shutdown();
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testGetAddress() throws Exception {
setupServiceInfo("http://cxf.apache.org/bindings/corba/simple","/wsdl_corbabinding/simpleIdl.wsdl","SimpleCORBAService","SimpleCORBAPort");
CorbaDestination destination=new CorbaDestination(endpointInfo,orbConfig);
endpointInfo.setAddress("corbaloc::localhost:40000/Simple");
CorbaServerConduit conduit=new CorbaServerConduit(endpointInfo,destination.getAddress(),targetObject,null,orbConfig,corbaTypeMap);
String address=conduit.getAddress();
assertTrue("address should not be null",address != null);
assertEquals(address,"corbaloc::localhost:40000/Simple");
}
Class: org.apache.cxf.binding.corba.CorbaTypeMapTest InternalCallVerifier EqualityVerifier
@Test public void testCorbaTypeMap() throws Exception {
CorbaTypeMap typeMap=new CorbaTypeMap("http://yoko.apache.org/ComplexTypes");
String targetNamespace=typeMap.getTargetNamespace();
assertEquals(targetNamespace,"http://yoko.apache.org/ComplexTypes");
QName type=new QName("http://yoko.apache.org/ComplexTypes","xsd1:Test.MultiPart.Colour","");
CorbaType corbaTypeImpl=new CorbaType();
corbaTypeImpl.setType(type);
corbaTypeImpl.setName("Test.MultiPart.Colour");
typeMap.addType("Test.MultiPart.Colour",corbaTypeImpl);
CorbaType corbatype=typeMap.getType("Test.MultiPart.Colour");
assertEquals(corbatype.getName(),"Test.MultiPart.Colour");
assertEquals(corbatype.getType().getLocalPart(),"xsd1:Test.MultiPart.Colour");
}
Class: org.apache.cxf.binding.corba.runtime.CorbaObjectReaderTest APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testReadObjectReference() throws IOException {
OutputStream oStream=orb.create_output_stream();
URL refUrl=getClass().getResource("/references/account.ref");
String oRef=IOUtils.toString(refUrl.openStream()).trim();
org.omg.CORBA.Object objRef=orb.string_to_object(oRef);
assertNotNull(objRef);
oStream.write_Object(objRef);
InputStream iStream=oStream.create_input_stream();
CorbaObjectReader reader=new CorbaObjectReader(iStream);
org.apache.cxf.binding.corba.wsdl.Object objectType=new org.apache.cxf.binding.corba.wsdl.Object();
objectType.setRepositoryID("IDL:Account:1.0");
objectType.setBinding(new QName("AccountCORBABinding"));
QName objectName=new QName("TestObject");
QName objectIdlType=new QName("corbaatm:TestObject");
TypeCode objectTC=orb.create_interface_tc("IDL:Account:1.0","TestObject");
CorbaObjectReferenceHandler obj=new CorbaObjectReferenceHandler(objectName,objectIdlType,objectTC,objectType);
reader.readObjectReference(obj);
assertTrue(obj.getReference()._is_equivalent(objRef));
}
InternalCallVerifier EqualityVerifier
@Test public void testReadULongLong(){
OutputStream oStream=orb.create_output_stream();
oStream.write_ulonglong(-1000000000L);
InputStream iStream=oStream.create_input_stream();
CorbaObjectReader reader=new CorbaObjectReader(iStream);
BigInteger ulonglongValue=reader.readULongLong();
assertEquals(1,ulonglongValue.signum());
}
BooleanVerifier InternalCallVerifier
@Test public void testReadLong(){
OutputStream oStream=orb.create_output_stream();
oStream.write_long(-100000);
InputStream iStream=oStream.create_input_stream();
CorbaObjectReader reader=new CorbaObjectReader(iStream);
Integer longValue=reader.readLong();
assertTrue(longValue.intValue() == -100000);
}
IterativeVerifier BooleanVerifier InternalCallVerifier PublicFieldVerifier
@Test public void testReadSequence(){
String data[]={"one","one","two","three","five","eight","thirteen","twenty-one"};
OutputStream oStream=orb.create_output_stream();
oStream.write_long(data.length);
for (int i=0; i < data.length; ++i) {
oStream.write_string(data[i]);
}
InputStream iStream=oStream.create_input_stream();
CorbaObjectReader reader=new CorbaObjectReader(iStream);
QName stringIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"string",CorbaConstants.NP_WSDL_CORBA);
QName seqIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"sequence",CorbaConstants.NP_WSDL_CORBA);
Sequence seqType=new Sequence();
seqType.setBound(data.length);
seqType.setElemtype(stringIdlType);
TypeCode seqTC=orb.create_sequence_tc(data.length,orb.get_primitive_tc(TCKind.tk_string));
CorbaSequenceHandler obj=new CorbaSequenceHandler(new QName("Seq"),seqIdlType,seqTC,seqType);
for (int i=0; i < data.length; ++i) {
CorbaPrimitiveHandler nestedObj=new CorbaPrimitiveHandler(new QName("item"),stringIdlType,orb.get_primitive_tc(TCKind.tk_string),null);
obj.addElement(nestedObj);
}
reader.readSequence(obj);
int length=obj.getElements().size();
for (int i=0; i < length; ++i) {
assertTrue(((CorbaPrimitiveHandler)obj.getElement(i)).getDataFromValue().equals(data[i]));
}
}
BooleanVerifier InternalCallVerifier
@Test public void testReadWChar(){
OutputStream oStream=orb.create_output_stream();
oStream.write_wchar('w');
InputStream iStream=oStream.create_input_stream();
CorbaObjectReader reader=new CorbaObjectReader(iStream);
Character wcharValue=reader.readWChar();
assertTrue(wcharValue.charValue() == 'w');
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testReadEnum(){
OutputStream oStream=orb.create_output_stream();
oStream.write_long(1);
InputStream iStream=oStream.create_input_stream();
CorbaObjectReader reader=new CorbaObjectReader(iStream);
String[] enums={"RED","GREEN","BLUE"};
Enum enumType=new Enum();
Enumerator enumRed=new Enumerator();
enumRed.setValue(enums[0]);
Enumerator enumGreen=new Enumerator();
enumGreen.setValue(enums[1]);
Enumerator enumBlue=new Enumerator();
enumBlue.setValue(enums[2]);
enumType.getEnumerator().add(enumRed);
enumType.getEnumerator().add(enumGreen);
enumType.getEnumerator().add(enumBlue);
QName enumName=new QName("TestEnum");
QName enumIdlType=new QName("corbatm:TestEnum");
TypeCode enumTC=orb.create_enum_tc("IDL:TestEnum:1.0",enumName.getLocalPart(),enums);
CorbaEnumHandler obj=new CorbaEnumHandler(enumName,enumIdlType,enumTC,enumType);
reader.readEnum(obj);
assertTrue(obj.getValue().equals(enums[1]));
}
BooleanVerifier InternalCallVerifier
@Test public void testReadWString(){
OutputStream oStream=orb.create_output_stream();
oStream.write_wstring("WString");
InputStream iStream=oStream.create_input_stream();
CorbaObjectReader reader=new CorbaObjectReader(iStream);
String wstringValue=reader.readWString();
assertTrue("WString".equals(wstringValue));
}
BooleanVerifier InternalCallVerifier
@Test public void testReadFixed(){
if (System.getProperty("java.vendor").contains("IBM")) {
return;
}
OutputStream oStream=orb.create_output_stream();
oStream.write_fixed(new java.math.BigDecimal("12345.67").movePointRight(2));
InputStream iStream=oStream.create_input_stream();
CorbaObjectReader reader=new CorbaObjectReader(iStream);
Fixed fixedType=new Fixed();
fixedType.setDigits(5);
fixedType.setScale(2);
QName fixedName=new QName("TestFixed");
QName fixedIdlType=new QName("corbatm:TestFixed");
TypeCode fixedTC=orb.create_fixed_tc((short)fixedType.getDigits(),(short)fixedType.getScale());
CorbaFixedHandler obj=new CorbaFixedHandler(fixedName,fixedIdlType,fixedTC,fixedType);
reader.readFixed(obj);
assertTrue(obj.getValue().equals(new java.math.BigDecimal("12345.67")));
}
BooleanVerifier InternalCallVerifier
@Test public void testReadStruct(){
OutputStream oStream=orb.create_output_stream();
int member1=12345;
String member2="54321";
boolean member3=true;
oStream.write_long(member1);
oStream.write_string(member2);
oStream.write_boolean(member3);
InputStream iStream=oStream.create_input_stream();
CorbaObjectReader reader=new CorbaObjectReader(iStream);
QName structIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"struct",CorbaConstants.NP_WSDL_CORBA);
QName longIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"long",CorbaConstants.NP_WSDL_CORBA);
QName stringIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"string",CorbaConstants.NP_WSDL_CORBA);
QName boolIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"boolean",CorbaConstants.NP_WSDL_CORBA);
Struct structType=new Struct();
structType.setName("TestStruct");
MemberType m1=new MemberType();
m1.setIdltype(longIdlType);
m1.setName("member1");
MemberType m2=new MemberType();
m2.setIdltype(stringIdlType);
m2.setName("member2");
MemberType m3=new MemberType();
m3.setIdltype(boolIdlType);
m3.setName("member3");
structType.getMember().add(m1);
structType.getMember().add(m2);
structType.getMember().add(m3);
StructMember[] structMembers=new StructMember[3];
structMembers[0]=new StructMember("member1",orb.get_primitive_tc(TCKind.tk_long),null);
structMembers[1]=new StructMember("member2",orb.get_primitive_tc(TCKind.tk_string),null);
structMembers[2]=new StructMember("member3",orb.get_primitive_tc(TCKind.tk_boolean),null);
TypeCode structTC=orb.create_struct_tc("IDL:org.apache.cxf.TestStruct/1.0","TestStruct",structMembers);
CorbaStructHandler obj=new CorbaStructHandler(new QName("TestStruct"),structIdlType,structTC,structType);
obj.addMember(new CorbaPrimitiveHandler(new QName("member1"),longIdlType,structMembers[0].type,null));
obj.addMember(new CorbaPrimitiveHandler(new QName("member2"),stringIdlType,structMembers[1].type,null));
obj.addMember(new CorbaPrimitiveHandler(new QName("member3"),boolIdlType,structMembers[2].type,null));
reader.readStruct(obj);
List nestedObjs=obj.getMembers();
assertTrue(new Integer(((CorbaPrimitiveHandler)nestedObjs.get(0)).getDataFromValue()).intValue() == member1);
assertTrue(((CorbaPrimitiveHandler)nestedObjs.get(1)).getDataFromValue().equals(member2));
assertTrue(Boolean.valueOf(((CorbaPrimitiveHandler)nestedObjs.get(2)).getDataFromValue()).booleanValue() == member3);
}
BooleanVerifier InternalCallVerifier
@Test public void testReadULong(){
OutputStream oStream=orb.create_output_stream();
oStream.write_ulong(100000);
InputStream iStream=oStream.create_input_stream();
CorbaObjectReader reader=new CorbaObjectReader(iStream);
long ulongValue=reader.readULong();
assertTrue(ulongValue == 100000);
}
BooleanVerifier InternalCallVerifier
@Test public void testReadDouble(){
OutputStream oStream=orb.create_output_stream();
oStream.write_double(6543.21);
InputStream iStream=oStream.create_input_stream();
CorbaObjectReader reader=new CorbaObjectReader(iStream);
Double doubleValue=reader.readDouble();
assertTrue(doubleValue.doubleValue() == 6543.21);
}
IterativeVerifier BooleanVerifier InternalCallVerifier PublicFieldVerifier
@Test public void testReadArray(){
int data[]={1,1,2,3,5,8,13,21};
OutputStream oStream=orb.create_output_stream();
oStream.write_long_array(data,0,data.length);
InputStream iStream=oStream.create_input_stream();
CorbaObjectReader reader=new CorbaObjectReader(iStream);
QName longIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"long",CorbaConstants.NP_WSDL_CORBA);
QName arrayIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"array",CorbaConstants.NP_WSDL_CORBA);
Array arrayType=new Array();
arrayType.setBound(data.length);
arrayType.setElemtype(longIdlType);
TypeCode arrayTC=orb.create_array_tc(data.length,orb.get_primitive_tc(TCKind.tk_long));
CorbaArrayHandler obj=new CorbaArrayHandler(new QName("Array"),arrayIdlType,arrayTC,arrayType);
for (int i=0; i < data.length; ++i) {
CorbaObjectHandler nestedObj=new CorbaPrimitiveHandler(new QName("item"),longIdlType,orb.get_primitive_tc(TCKind.tk_long),null);
obj.addElement(nestedObj);
}
reader.readArray(obj);
int length=obj.getElements().size();
for (int i=0; i < length; ++i) {
assertTrue(new Long(((CorbaPrimitiveHandler)obj.getElement(i)).getDataFromValue()).intValue() == data[i]);
}
}
BooleanVerifier InternalCallVerifier
@Test public void testReadOctet(){
OutputStream oStream=orb.create_output_stream();
oStream.write_octet((byte)27);
InputStream iStream=oStream.create_input_stream();
CorbaObjectReader reader=new CorbaObjectReader(iStream);
Byte octetValue=reader.readOctet();
assertTrue(octetValue.byteValue() == (byte)27);
}
BooleanVerifier InternalCallVerifier
@Test public void testReadLongLong(){
OutputStream oStream=orb.create_output_stream();
oStream.write_longlong(1000000000);
InputStream iStream=oStream.create_input_stream();
CorbaObjectReader reader=new CorbaObjectReader(iStream);
Long longlongValue=reader.readLongLong();
assertTrue(longlongValue.longValue() == 1000000000);
}
BooleanVerifier InternalCallVerifier
@Test public void testReadBoolean(){
OutputStream oStream=orb.create_output_stream();
oStream.write_boolean(true);
InputStream iStream=oStream.create_input_stream();
CorbaObjectReader reader=new CorbaObjectReader(iStream);
Boolean boolValue=reader.readBoolean();
assertTrue(boolValue.booleanValue());
}
BooleanVerifier InternalCallVerifier
@Test public void testReadString(){
OutputStream oStream=orb.create_output_stream();
oStream.write_string("String");
InputStream iStream=oStream.create_input_stream();
CorbaObjectReader reader=new CorbaObjectReader(iStream);
String stringValue=reader.readString();
assertTrue("String".equals(stringValue));
}
BooleanVerifier InternalCallVerifier
@Test public void testReadChar(){
OutputStream oStream=orb.create_output_stream();
oStream.write_char('c');
InputStream iStream=oStream.create_input_stream();
CorbaObjectReader reader=new CorbaObjectReader(iStream);
Character charValue=reader.readChar();
assertTrue(charValue.charValue() == 'c');
}
BooleanVerifier InternalCallVerifier
@Test public void testReadException(){
OutputStream oStream=orb.create_output_stream();
short code=12345;
String message="54321";
oStream.write_string("IDL:org.apache.cxf.TestException/1.0");
oStream.write_short(code);
oStream.write_string(message);
InputStream iStream=oStream.create_input_stream();
CorbaObjectReader reader=new CorbaObjectReader(iStream);
QName exceptIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"exception",CorbaConstants.NP_WSDL_CORBA);
QName shortIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"short",CorbaConstants.NP_WSDL_CORBA);
QName stringIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"string",CorbaConstants.NP_WSDL_CORBA);
Exception exceptType=new Exception();
exceptType.setName("TestException");
MemberType m1=new MemberType();
m1.setIdltype(shortIdlType);
m1.setName("code");
MemberType m2=new MemberType();
m2.setIdltype(stringIdlType);
m2.setName("message");
exceptType.getMember().add(m1);
exceptType.getMember().add(m2);
StructMember[] exceptMembers=new StructMember[2];
exceptMembers[0]=new StructMember("code",orb.get_primitive_tc(TCKind.tk_short),null);
exceptMembers[1]=new StructMember("message",orb.get_primitive_tc(TCKind.tk_string),null);
TypeCode exceptTC=orb.create_exception_tc("IDL:org.apache.cxf.TestException/1.0","TestException",exceptMembers);
CorbaExceptionHandler obj=new CorbaExceptionHandler(new QName("TestException"),exceptIdlType,exceptTC,exceptType);
obj.addMember(new CorbaPrimitiveHandler(new QName("code"),shortIdlType,exceptMembers[0].type,null));
obj.addMember(new CorbaPrimitiveHandler(new QName("message"),stringIdlType,exceptMembers[1].type,null));
reader.readException(obj);
List nestedObjs=obj.getMembers();
assertTrue(new Short(((CorbaPrimitiveHandler)nestedObjs.get(0)).getDataFromValue()).shortValue() == code);
assertTrue(((CorbaPrimitiveHandler)nestedObjs.get(1)).getDataFromValue().equals(message));
}
BooleanVerifier InternalCallVerifier
@Test public void testReadShort(){
OutputStream oStream=orb.create_output_stream();
oStream.write_short((short)-100);
InputStream iStream=oStream.create_input_stream();
CorbaObjectReader reader=new CorbaObjectReader(iStream);
Short shortValue=reader.readShort();
assertTrue(shortValue.shortValue() == (short)-100);
}
BooleanVerifier InternalCallVerifier
@Test public void testReadUShort(){
OutputStream oStream=orb.create_output_stream();
oStream.write_ushort((short)100);
InputStream iStream=oStream.create_input_stream();
CorbaObjectReader reader=new CorbaObjectReader(iStream);
Integer ushortValue=reader.readUShort();
assertTrue(ushortValue.intValue() == 100);
}
BooleanVerifier InternalCallVerifier
@Test public void testReadFloat(){
OutputStream oStream=orb.create_output_stream();
oStream.write_float((float)1234.56);
InputStream iStream=oStream.create_input_stream();
CorbaObjectReader reader=new CorbaObjectReader(iStream);
Float floatValue=reader.readFloat();
assertTrue(floatValue.floatValue() == (float)1234.56);
}
Class: org.apache.cxf.binding.corba.runtime.CorbaObjectWriterTest BooleanVerifier InternalCallVerifier
@Test public void testWriteDouble(){
OutputStream oStream=orb.create_output_stream();
CorbaObjectWriter writer=new CorbaObjectWriter(oStream);
Double doubleValue=new Double(987654.321);
writer.writeDouble(doubleValue);
InputStream iStream=oStream.create_input_stream();
double d=iStream.read_double();
assertTrue(d == doubleValue.doubleValue());
}
BooleanVerifier InternalCallVerifier
@Test public void testWriteULong(){
OutputStream oStream=orb.create_output_stream();
CorbaObjectWriter writer=new CorbaObjectWriter(oStream);
long ulongValue=1234567L;
writer.writeULong(ulongValue);
InputStream iStream=oStream.create_input_stream();
long ul=iStream.read_ulong();
assertTrue(ul == ulongValue);
}
BooleanVerifier InternalCallVerifier
@Test public void testWriteFloat(){
OutputStream oStream=orb.create_output_stream();
CorbaObjectWriter writer=new CorbaObjectWriter(oStream);
Float floatValue=new Float((float)123456.78);
writer.writeFloat(floatValue);
InputStream iStream=oStream.create_input_stream();
float f=iStream.read_float();
assertTrue(f == floatValue.floatValue());
}
BooleanVerifier InternalCallVerifier
@Test public void testWriteShort(){
OutputStream oStream=orb.create_output_stream();
CorbaObjectWriter writer=new CorbaObjectWriter(oStream);
Short shortValue=new Short((short)-123);
writer.writeShort(shortValue);
InputStream iStream=oStream.create_input_stream();
short s=iStream.read_short();
assertTrue(s == shortValue.shortValue());
}
IterativeVerifier BooleanVerifier InternalCallVerifier
@Test public void testWriteArray(){
int data[]={1,1,2,3,5,8,13,21};
QName longIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"long",CorbaConstants.NP_WSDL_CORBA);
QName arrayIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"array",CorbaConstants.NP_WSDL_CORBA);
Array arrayType=new Array();
arrayType.setBound(data.length);
arrayType.setElemtype(longIdlType);
TypeCode arrayTC=orb.create_array_tc(data.length,orb.get_primitive_tc(TCKind.tk_long));
CorbaArrayHandler obj=new CorbaArrayHandler(new QName("Array"),arrayIdlType,arrayTC,arrayType);
for (int i=0; i < data.length; ++i) {
CorbaPrimitiveHandler nestedObj=new CorbaPrimitiveHandler(new QName("item"),longIdlType,orb.get_primitive_tc(TCKind.tk_long),null);
nestedObj.setValueFromData(Integer.toString(data[i]));
obj.addElement(nestedObj);
}
OutputStream oStream=orb.create_output_stream();
CorbaObjectWriter writer=new CorbaObjectWriter(oStream);
writer.writeArray(obj);
InputStream iStream=oStream.create_input_stream();
for (int i=0; i < data.length; ++i) {
int val=iStream.read_long();
assertTrue(val == data[i]);
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testWriteString(){
OutputStream oStream=orb.create_output_stream();
CorbaObjectWriter writer=new CorbaObjectWriter(oStream);
String stringValue=new String("String");
writer.writeString(stringValue);
InputStream iStream=oStream.create_input_stream();
String s=iStream.read_string();
assertTrue(s.equals(stringValue));
}
APIUtilityVerifier IterativeVerifier BooleanVerifier InternalCallVerifier
@Test public void testWriteSequence(){
String data[]={"one","one","two","three","five","eight","thirteen","twenty-one"};
QName stringIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"string",CorbaConstants.NP_WSDL_CORBA);
QName seqIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"sequence",CorbaConstants.NP_WSDL_CORBA);
Sequence seqType=new Sequence();
seqType.setBound(data.length);
seqType.setElemtype(stringIdlType);
TypeCode seqTC=orb.create_sequence_tc(data.length,orb.get_primitive_tc(TCKind.tk_string));
CorbaSequenceHandler obj=new CorbaSequenceHandler(new QName("Seq"),seqIdlType,seqTC,seqType);
for (int i=0; i < data.length; ++i) {
CorbaPrimitiveHandler nestedObj=new CorbaPrimitiveHandler(new QName("item"),stringIdlType,orb.get_primitive_tc(TCKind.tk_string),null);
nestedObj.setValueFromData(data[i]);
obj.addElement(nestedObj);
}
OutputStream oStream=orb.create_output_stream();
CorbaObjectWriter writer=new CorbaObjectWriter(oStream);
writer.writeSequence(obj);
InputStream iStream=oStream.create_input_stream();
int length=iStream.read_long();
for (int i=0; i < length; ++i) {
String val=iStream.read_string();
assertTrue(val.equals(data[i]));
}
}
BooleanVerifier InternalCallVerifier
@Test public void testWriteUShort(){
OutputStream oStream=orb.create_output_stream();
CorbaObjectWriter writer=new CorbaObjectWriter(oStream);
Integer ushortValue=new Integer(123);
writer.writeUShort(ushortValue);
InputStream iStream=oStream.create_input_stream();
int us=iStream.read_ushort();
assertTrue(us == ushortValue.intValue());
}
BooleanVerifier InternalCallVerifier
@Test public void testWriteLongLong(){
OutputStream oStream=orb.create_output_stream();
CorbaObjectWriter writer=new CorbaObjectWriter(oStream);
Long longlongValue=new Long("-12345678900");
writer.writeLongLong(longlongValue);
InputStream iStream=oStream.create_input_stream();
long ll=iStream.read_longlong();
assertTrue(ll == longlongValue.longValue());
}
BooleanVerifier InternalCallVerifier
@Test public void testWriteULongLong(){
OutputStream oStream=orb.create_output_stream();
CorbaObjectWriter writer=new CorbaObjectWriter(oStream);
BigInteger ulonglongValue=new BigInteger("12345678900");
writer.writeULongLong(ulonglongValue);
InputStream iStream=oStream.create_input_stream();
long ul=iStream.read_ulonglong();
assertTrue(ul == ulonglongValue.longValue());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testWriteStruct(){
int member1=12345;
String member2="54321";
boolean member3=true;
QName structIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"struct",CorbaConstants.NP_WSDL_CORBA);
QName longIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"long",CorbaConstants.NP_WSDL_CORBA);
QName stringIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"string",CorbaConstants.NP_WSDL_CORBA);
QName boolIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"boolean",CorbaConstants.NP_WSDL_CORBA);
Struct structType=new Struct();
structType.setName("TestStruct");
MemberType m1=new MemberType();
m1.setIdltype(longIdlType);
m1.setName("member1");
MemberType m2=new MemberType();
m2.setIdltype(stringIdlType);
m2.setName("member2");
MemberType m3=new MemberType();
m3.setIdltype(boolIdlType);
m3.setName("member3");
structType.getMember().add(m1);
structType.getMember().add(m2);
structType.getMember().add(m3);
StructMember[] structMembers=new StructMember[3];
structMembers[0]=new StructMember("member1",orb.get_primitive_tc(TCKind.tk_long),null);
structMembers[1]=new StructMember("member2",orb.get_primitive_tc(TCKind.tk_string),null);
structMembers[2]=new StructMember("member3",orb.get_primitive_tc(TCKind.tk_boolean),null);
TypeCode structTC=orb.create_struct_tc("IDL:org.apache.cxf.TestStruct/1.0","TestStruct",structMembers);
CorbaStructHandler obj=new CorbaStructHandler(new QName("TestStruct"),structIdlType,structTC,structType);
CorbaPrimitiveHandler memberObj1=new CorbaPrimitiveHandler(new QName("member1"),longIdlType,structMembers[0].type,null);
CorbaPrimitiveHandler memberObj2=new CorbaPrimitiveHandler(new QName("member2"),stringIdlType,structMembers[1].type,null);
CorbaPrimitiveHandler memberObj3=new CorbaPrimitiveHandler(new QName("member3"),boolIdlType,structMembers[2].type,null);
memberObj1.setValueFromData(Integer.toString(member1));
memberObj2.setValueFromData(member2);
memberObj3.setValueFromData(Boolean.toString(member3));
obj.addMember(memberObj1);
obj.addMember(memberObj2);
obj.addMember(memberObj3);
OutputStream oStream=orb.create_output_stream();
CorbaObjectWriter writer=new CorbaObjectWriter(oStream);
writer.writeStruct(obj);
InputStream iStream=oStream.create_input_stream();
int readMember1=iStream.read_long();
assertTrue(readMember1 == member1);
String readMember2=iStream.read_string();
assertTrue(readMember2.equals(member2));
boolean readMember3=iStream.read_boolean();
assertTrue(readMember3 == member3);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testWriteObject() throws IOException {
URL refUrl=getClass().getResource("/references/account.ref");
String oRef=IOUtils.toString(refUrl.openStream()).trim();
org.omg.CORBA.Object objRef=orb.string_to_object(oRef);
assertNotNull(objRef);
org.apache.cxf.binding.corba.wsdl.Object objectType=new org.apache.cxf.binding.corba.wsdl.Object();
objectType.setRepositoryID("IDL:Account:1.0");
objectType.setBinding(new QName("AccountCORBABinding"));
QName objectName=new QName("TestObject");
QName objectIdlType=new QName("corbaatm:TestObject");
TypeCode objectTC=orb.create_interface_tc("IDL:Account:1.0","TestObject");
CorbaObjectReferenceHandler obj=new CorbaObjectReferenceHandler(objectName,objectIdlType,objectTC,objectType);
obj.setReference(objRef);
OutputStream oStream=orb.create_output_stream();
CorbaObjectWriter writer=new CorbaObjectWriter(oStream);
writer.writeObjectReference(obj);
InputStream iStream=oStream.create_input_stream();
org.omg.CORBA.Object resultObj=iStream.read_Object();
assertTrue(resultObj._is_equivalent(obj.getReference()));
}
BooleanVerifier InternalCallVerifier
@Test public void testWriteWChar(){
OutputStream oStream=orb.create_output_stream();
CorbaObjectWriter writer=new CorbaObjectWriter(oStream);
Character wcharValue=new Character('w');
writer.writeChar(wcharValue);
InputStream iStream=oStream.create_input_stream();
char wc=iStream.read_char();
assertTrue(wc == wcharValue.charValue());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testWriteException(){
short code=12345;
String message="54321";
String reposID="IDL:org.apache.cxf.TestException/1.0";
QName exceptIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"exception",CorbaConstants.NP_WSDL_CORBA);
QName shortIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"short",CorbaConstants.NP_WSDL_CORBA);
QName stringIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"string",CorbaConstants.NP_WSDL_CORBA);
Exception exceptType=new Exception();
exceptType.setName("TestException");
exceptType.setRepositoryID(reposID);
MemberType m1=new MemberType();
m1.setIdltype(shortIdlType);
m1.setName("code");
MemberType m2=new MemberType();
m2.setIdltype(stringIdlType);
m2.setName("message");
exceptType.getMember().add(m1);
exceptType.getMember().add(m2);
StructMember[] exceptMembers=new StructMember[2];
exceptMembers[0]=new StructMember("code",orb.get_primitive_tc(TCKind.tk_short),null);
exceptMembers[1]=new StructMember("message",orb.get_primitive_tc(TCKind.tk_string),null);
TypeCode exceptTC=orb.create_exception_tc(reposID,"TestException",exceptMembers);
CorbaExceptionHandler obj=new CorbaExceptionHandler(new QName("TestException"),exceptIdlType,exceptTC,exceptType);
CorbaPrimitiveHandler member1=new CorbaPrimitiveHandler(new QName("code"),shortIdlType,exceptMembers[0].type,null);
member1.setValueFromData(Short.toString(code));
CorbaPrimitiveHandler member2=new CorbaPrimitiveHandler(new QName("message"),stringIdlType,exceptMembers[1].type,null);
member2.setValueFromData(message);
obj.addMember(member1);
obj.addMember(member2);
OutputStream oStream=orb.create_output_stream();
CorbaObjectWriter writer=new CorbaObjectWriter(oStream);
writer.writeException(obj);
InputStream iStream=oStream.create_input_stream();
String readId=iStream.read_string();
assertTrue(readId.equals(reposID));
short readCode=iStream.read_short();
assertTrue(readCode == code);
String readMessage=iStream.read_string();
assertTrue(readMessage.equals(message));
}
BooleanVerifier InternalCallVerifier
@Test public void testWriteBoolean(){
OutputStream oStream=orb.create_output_stream();
CorbaObjectWriter writer=new CorbaObjectWriter(oStream);
Boolean boolValue=Boolean.TRUE;
writer.writeBoolean(boolValue);
InputStream iStream=oStream.create_input_stream();
boolean b=iStream.read_boolean();
assertTrue(b == boolValue.booleanValue());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testWriteWString(){
OutputStream oStream=orb.create_output_stream();
CorbaObjectWriter writer=new CorbaObjectWriter(oStream);
String wstringValue=new String("String");
writer.writeWString(wstringValue);
InputStream iStream=oStream.create_input_stream();
String s=iStream.read_wstring();
assertTrue(s.equals(wstringValue));
}
BooleanVerifier InternalCallVerifier
@Test public void testWriteLong(){
OutputStream oStream=orb.create_output_stream();
CorbaObjectWriter writer=new CorbaObjectWriter(oStream);
Integer longValue=new Integer(-1234567);
writer.writeLong(longValue);
InputStream iStream=oStream.create_input_stream();
int l=iStream.read_long();
assertTrue(l == longValue.intValue());
}
BooleanVerifier InternalCallVerifier
@Test public void testWriteChar(){
OutputStream oStream=orb.create_output_stream();
CorbaObjectWriter writer=new CorbaObjectWriter(oStream);
Character charValue=new Character('c');
writer.writeChar(charValue);
InputStream iStream=oStream.create_input_stream();
char c=iStream.read_char();
assertTrue(c == charValue.charValue());
}
Class: org.apache.cxf.binding.corba.runtime.CorbaStreamableTest BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testGetStreamableAttributes(){
QName objName=new QName("object");
QName objIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"float",CorbaConstants.NP_WSDL_CORBA);
TypeCode objTypeCode=orb.get_primitive_tc(TCKind.tk_float);
CorbaPrimitiveHandler obj=new CorbaPrimitiveHandler(objName,objIdlType,objTypeCode,null);
CorbaStreamable streamable=new CorbaStreamableImpl(obj,objName);
TypeCode type=streamable._type();
assertTrue(type.kind().value() == objTypeCode.kind().value());
CorbaPrimitiveHandler storedObj=(CorbaPrimitiveHandler)streamable.getObject();
assertNotNull(storedObj);
int mode=streamable.getMode();
assertTrue(mode == org.omg.CORBA.ARG_OUT.value);
String name=streamable.getName();
assertTrue(name.equals(objName.getLocalPart()));
}
BooleanVerifier InternalCallVerifier
@Test public void testSetStreamableAttributes(){
QName objName=new QName("object");
QName objIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"boolean",CorbaConstants.NP_WSDL_CORBA);
TypeCode objTypeCode=orb.get_primitive_tc(TCKind.tk_boolean);
CorbaPrimitiveHandler obj=new CorbaPrimitiveHandler(objName,objIdlType,objTypeCode,null);
CorbaStreamable streamable=new CorbaStreamableImpl(obj,objName);
streamable.setMode(org.omg.CORBA.ARG_IN.value);
int mode=streamable.getMode();
assertTrue(mode == org.omg.CORBA.ARG_IN.value);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testWriteStreamable(){
QName objName=new QName("object");
QName objIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"wstring",CorbaConstants.NP_WSDL_CORBA);
TypeCode objTypeCode=orb.get_primitive_tc(TCKind.tk_wstring);
CorbaPrimitiveHandler obj=new CorbaPrimitiveHandler(objName,objIdlType,objTypeCode,null);
obj.setValueFromData("TestWString");
CorbaStreamable streamable=new CorbaStreamableImpl(obj,objName);
OutputStream oStream=orb.create_output_stream();
streamable._write(oStream);
InputStream iStream=oStream.create_input_stream();
String value=iStream.read_wstring();
assertEquals("TestWString",value);
}
InternalCallVerifier NullVerifier
@Test public void testCreateStreamable(){
QName objName=new QName("object");
QName objIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"short",CorbaConstants.NP_WSDL_CORBA);
TypeCode objTypeCode=orb.get_primitive_tc(TCKind.tk_short);
CorbaPrimitiveHandler obj=new CorbaPrimitiveHandler(objName,objIdlType,objTypeCode,null);
CorbaStreamable streamable=new CorbaStreamableImpl(obj,objName);
assertNotNull(streamable);
}
BooleanVerifier InternalCallVerifier
@Test public void testReadStreamable(){
QName objName=new QName("object");
QName objIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"char",CorbaConstants.NP_WSDL_CORBA);
TypeCode objTypeCode=orb.get_primitive_tc(TCKind.tk_char);
CorbaPrimitiveHandler obj=new CorbaPrimitiveHandler(objName,objIdlType,objTypeCode,null);
CorbaStreamable streamable=new CorbaStreamableImpl(obj,objName);
OutputStream oStream=orb.create_output_stream();
oStream.write_char('c');
InputStream iStream=oStream.create_input_stream();
streamable._read(iStream);
CorbaPrimitiveHandler streamableObj=(CorbaPrimitiveHandler)streamable.getObject();
Object o=streamableObj.getValue();
assertTrue(o instanceof Character);
Character charValue=(Character)o;
assertTrue(charValue.charValue() == 'c');
}
Class: org.apache.cxf.binding.corba.types.CorbaAnyHandlerTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCorbaAnyHandler(){
Any a=orb.create_any();
a.insert_string("TestMessage");
QName anyName=new QName("AnyHandlerName");
QName anyIdlType=CorbaConstants.NT_CORBA_ANY;
TypeCode anyTC=orb.get_primitive_tc(TCKind.from_int(TCKind._tk_any));
CorbaTypeMap tm=new CorbaTypeMap(CorbaConstants.NU_WSDL_CORBA);
CorbaAnyHandler anyHandler=new CorbaAnyHandler(anyName,anyIdlType,anyTC,null);
anyHandler.setTypeMap(tm);
anyHandler.setValue(a);
Any resultAny=anyHandler.getValue();
assertNotNull(resultAny);
String value=resultAny.extract_string();
assertEquals("TestMessage",value);
CorbaTypeMap resultTM=anyHandler.getTypeMap();
assertTrue(resultTM.getTargetNamespace().equals(CorbaConstants.NU_WSDL_CORBA));
}
Class: org.apache.cxf.binding.corba.types.CorbaArrayHandlerTest IterativeVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testArrayHandler(){
objName=new QName("object");
objIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"arrayType",CorbaConstants.NP_WSDL_CORBA);
objTypeCode=orb.create_array_tc(5,orb.get_primitive_tc(TCKind.tk_long));
Array arrayType=new Array();
arrayType.setName("arrayType");
arrayType.setElemtype(CorbaConstants.NT_CORBA_LONG);
arrayType.setBound(5);
arrayType.setRepositoryID("IDL:ArrayType:1.0");
obj=new CorbaArrayHandler(objName,objIdlType,objTypeCode,arrayType);
assertNotNull(obj);
int arrayData[]={2,4,6,8,10};
for (int i=0; i < arrayData.length; ++i) {
QName elName=new QName("item");
QName elIdlType=CorbaConstants.NT_CORBA_LONG;
TypeCode elTC=orb.get_primitive_tc(TCKind.tk_long);
CorbaPrimitiveHandler el=new CorbaPrimitiveHandler(elName,elIdlType,elTC,null);
el.setValue(Integer.valueOf(arrayData[i]));
obj.addElement(el);
}
QName nameResult=obj.getName();
assertNotNull(nameResult);
assertTrue(objName.equals(nameResult));
QName idlTypeResult=obj.getIdlType();
assertNotNull(idlTypeResult);
assertTrue(idlTypeResult.equals(objIdlType));
TypeCode tcResult=obj.getTypeCode();
assertNotNull(tcResult);
assertTrue(tcResult.kind().value() == objTypeCode.kind().value());
Object objDefResult=obj.getType();
assertNotNull(objDefResult);
assertTrue(objDefResult instanceof Array);
int countResult=obj.getNumberOfElements();
for (int i=0; i < countResult; ++i) {
CorbaObjectHandler elResult=obj.getElement(i);
assertNotNull(elResult);
}
}
Class: org.apache.cxf.binding.corba.types.CorbaEnumHandlerTest APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testCorbaEnumHandler(){
Enum enumType=new Enum();
enumType.setName("EnumType");
enumType.setRepositoryID("IDL:EnumType:1.0");
Enumerator enumerator0=new Enumerator();
enumerator0.setValue("ENUM0");
Enumerator enumerator1=new Enumerator();
enumerator1.setValue("ENUM1");
Enumerator enumerator2=new Enumerator();
enumerator2.setValue("ENUM2");
enumType.getEnumerator().add(enumerator0);
enumType.getEnumerator().add(enumerator1);
enumType.getEnumerator().add(enumerator2);
QName enumName=new QName("EnumType");
QName enumIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"EnumType",CorbaConstants.NP_WSDL_CORBA);
String members[]=new String[3];
members[0]=enumerator0.getValue();
members[1]=enumerator1.getValue();
members[2]=enumerator2.getValue();
TypeCode enumTC=orb.create_enum_tc(enumType.getRepositoryID(),enumType.getName(),members);
CorbaEnumHandler obj=new CorbaEnumHandler(enumName,enumIdlType,enumTC,enumType);
assertNotNull(obj);
obj.setValue(members[1]);
assertTrue(obj.getValue().equals(enumerator1.getValue()));
assertTrue(obj.getIndex() == 1);
}
Class: org.apache.cxf.binding.corba.types.CorbaFixedHandlerTest BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testCorbaFixedHandler(){
Fixed fixedType=new Fixed();
fixedType.setName("FixedType");
fixedType.setDigits(3);
fixedType.setScale(2);
QName fixedName=new QName(fixedType.getName());
QName fixedIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"FixedType",CorbaConstants.NP_WSDL_CORBA);
TypeCode fixedTC=orb.create_fixed_tc((short)fixedType.getDigits(),(short)fixedType.getScale());
CorbaFixedHandler obj=new CorbaFixedHandler(fixedName,fixedIdlType,fixedTC,fixedType);
assertNotNull(obj);
java.math.BigDecimal value=new java.math.BigDecimal(123.45);
obj.setValue(value);
assertTrue(value.equals(obj.getValue()));
String valueData=obj.getValueData();
assertTrue(valueData.equals(value.toString()));
assertTrue(fixedType.getDigits() == obj.getDigits());
assertTrue(fixedType.getScale() == obj.getScale());
}
Class: org.apache.cxf.binding.corba.types.CorbaHandlerUtilsTest APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testInitializeObjectHandler(){
QName objName=null;
QName objIdlType=null;
CorbaObjectHandler result=null;
objName=new QName("object");
objIdlType=new QName(complexTypesNamespaceURI,"TestArray",complexTypesPrefix);
result=CorbaHandlerUtils.initializeObjectHandler(orb,objName,objIdlType,typeMap,service);
assertTrue(result instanceof CorbaArrayHandler);
CorbaArrayHandler arrayHandler=(CorbaArrayHandler)result;
assertTrue(arrayHandler.getElements().size() == 5);
objName=new QName("object");
objIdlType=new QName(complexTypesNamespaceURI,"TestSequence",complexTypesPrefix);
result=CorbaHandlerUtils.initializeObjectHandler(orb,objName,objIdlType,typeMap,service);
assertTrue(result instanceof CorbaSequenceHandler);
CorbaSequenceHandler seqHandler=(CorbaSequenceHandler)result;
assertTrue(seqHandler.getElements().size() == 0);
assertNotNull(seqHandler.getTemplateElement());
objName=new QName("object");
objIdlType=new QName(complexTypesNamespaceURI,"TestBoundedSequence",complexTypesPrefix);
result=CorbaHandlerUtils.initializeObjectHandler(orb,objName,objIdlType,typeMap,service);
assertTrue(result instanceof CorbaSequenceHandler);
CorbaSequenceHandler boundedSeqHandler=(CorbaSequenceHandler)result;
assertTrue(boundedSeqHandler.getElements().size() == 5);
objName=new QName("object");
objIdlType=new QName(complexTypesNamespaceURI,"TestStruct",complexTypesPrefix);
result=CorbaHandlerUtils.initializeObjectHandler(orb,objName,objIdlType,typeMap,service);
assertTrue(result instanceof CorbaStructHandler);
CorbaStructHandler structHandler=(CorbaStructHandler)result;
assertTrue(structHandler.getMembers().size() == 3);
objName=new QName("object");
objIdlType=new QName(complexTypesNamespaceURI,"TestUnion",complexTypesPrefix);
result=CorbaHandlerUtils.initializeObjectHandler(orb,objName,objIdlType,typeMap,service);
assertTrue(result instanceof CorbaUnionHandler);
}
Class: org.apache.cxf.binding.corba.types.CorbaObjectHandlerTest BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testGetObjectAttributes(){
QName objName=new QName("object");
QName objIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"long",CorbaConstants.NP_WSDL_CORBA);
TypeCode objTypeCode=orb.get_primitive_tc(TCKind.tk_long);
CorbaObjectHandler obj=new CorbaObjectHandler(objName,objIdlType,objTypeCode,null);
QName name=obj.getName();
assertNotNull(name);
assertTrue(name.equals(objName));
QName idlType=obj.getIdlType();
assertNotNull(idlType);
assertTrue(idlType.equals(objIdlType));
TypeCode tc=obj.getTypeCode();
assertNotNull(tc);
assertTrue(tc.kind().value() == objTypeCode.kind().value());
Object objDef=obj.getType();
assertNull(objDef);
}
InternalCallVerifier NullVerifier
@Test public void testCreateCorbaObjectHandler(){
QName objName=new QName("object");
QName objIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"long",CorbaConstants.NP_WSDL_CORBA);
TypeCode objTypeCode=orb.get_primitive_tc(TCKind.tk_long);
CorbaObjectHandler obj=new CorbaObjectHandler(objName,objIdlType,objTypeCode,null);
assertNotNull(obj);
}
Class: org.apache.cxf.binding.corba.types.CorbaPrimitiveHandlerTest BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testCreateCorbaULongLong(){
Long val=new Long(987654321);
CorbaPrimitiveHandler obj=new CorbaPrimitiveHandler(new QName("ulonglong"),CorbaConstants.NT_CORBA_ULONGLONG,orb.get_primitive_tc(TCKind.tk_ulonglong),null);
assertNotNull(obj);
obj.setValueFromData(val.toString());
String result=obj.getDataFromValue();
assertTrue(val.toString().equals(result));
obj.setValue(val);
Object resultObj=obj.getValue();
assertNotNull(resultObj);
assertTrue(resultObj instanceof Long);
Long longlongResult=(Long)resultObj;
assertTrue(longlongResult.longValue() == val.longValue());
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testCreateCorbaWChararacter(){
Character val=new Character('w');
CorbaPrimitiveHandler obj=new CorbaPrimitiveHandler(new QName("wchar"),CorbaConstants.NT_CORBA_WCHAR,orb.get_primitive_tc(TCKind.tk_wchar),null);
assertNotNull(obj);
obj.setValueFromData("w");
String result=obj.getDataFromValue();
assertTrue(val.charValue() == result.charAt(0));
obj.setValue(val);
Object resultObj=obj.getValue();
assertNotNull(resultObj);
assertTrue(resultObj instanceof Character);
Character charResult=(Character)resultObj;
assertTrue(charResult.charValue() == val.charValue());
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testCreateCorbaLongLong(){
Long val=new Long(123456789);
CorbaPrimitiveHandler obj=new CorbaPrimitiveHandler(new QName("longlong"),CorbaConstants.NT_CORBA_LONGLONG,orb.get_primitive_tc(TCKind.tk_longlong),null);
assertNotNull(obj);
obj.setValueFromData(val.toString());
String result=obj.getDataFromValue();
assertTrue(val.toString().equals(result));
obj.setValue(val);
Object resultObj=obj.getValue();
assertNotNull(resultObj);
assertTrue(resultObj instanceof Long);
Long longlongResult=(Long)resultObj;
assertTrue(longlongResult.longValue() == val.longValue());
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testCreateCorbaUShort(){
Short val=new Short((short)4321);
CorbaPrimitiveHandler obj=new CorbaPrimitiveHandler(new QName("ushort"),CorbaConstants.NT_CORBA_USHORT,orb.get_primitive_tc(TCKind.tk_ushort),null);
assertNotNull(obj);
obj.setValueFromData(val.toString());
String result=obj.getDataFromValue();
assertTrue(val.toString().equals(result));
obj.setValue(val);
Object resultObj=obj.getValue();
assertNotNull(resultObj);
assertTrue(resultObj instanceof Short);
Short shortResult=(Short)resultObj;
assertTrue(shortResult.shortValue() == val.shortValue());
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testCreateCorbaString(){
String val="Test String";
CorbaPrimitiveHandler obj=new CorbaPrimitiveHandler(new QName("string"),CorbaConstants.NT_CORBA_STRING,orb.get_primitive_tc(TCKind.tk_string),null);
assertNotNull(obj);
obj.setValueFromData(val.toString());
String result=obj.getDataFromValue();
assertTrue(val.equals(result));
obj.setValue(val);
Object resultObj=obj.getValue();
assertNotNull(resultObj);
assertTrue(resultObj instanceof String);
String stringResult=(String)resultObj;
assertTrue(stringResult.equals(val));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testCreateCorbaChararacter(){
Character val=new Character('c');
CorbaPrimitiveHandler obj=new CorbaPrimitiveHandler(new QName("char"),CorbaConstants.NT_CORBA_CHAR,orb.get_primitive_tc(TCKind.tk_char),null);
assertNotNull(obj);
Byte byteValue=new Byte((byte)val.charValue());
obj.setValueFromData(byteValue.toString());
String result=obj.getDataFromValue();
Byte byteResult=new Byte(result);
assertTrue(byteResult.byteValue() == byteValue.byteValue());
obj.setValue(val);
Object resultObj=obj.getValue();
assertNotNull(resultObj);
assertTrue(resultObj instanceof Character);
Character charResult=(Character)resultObj;
assertTrue(charResult.charValue() == val.charValue());
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testCreateCorbaWString(){
String val="Test Wide String";
CorbaPrimitiveHandler obj=new CorbaPrimitiveHandler(new QName("wstring"),CorbaConstants.NT_CORBA_WSTRING,orb.get_primitive_tc(TCKind.tk_wstring),null);
assertNotNull(obj);
obj.setValueFromData(val.toString());
String result=obj.getDataFromValue();
assertTrue(val.equals(result));
obj.setValue(val);
Object resultObj=obj.getValue();
assertNotNull(resultObj);
assertTrue(resultObj instanceof String);
String stringResult=(String)resultObj;
assertTrue(stringResult.equals(val));
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testCreateCorbaDouble(){
Double val=new Double(123456.789);
CorbaPrimitiveHandler obj=new CorbaPrimitiveHandler(new QName("double"),CorbaConstants.NT_CORBA_DOUBLE,orb.get_primitive_tc(TCKind.tk_double),null);
assertNotNull(obj);
obj.setValueFromData(val.toString());
String result=obj.getDataFromValue();
assertTrue(val.toString().equals(result));
obj.setValue(val);
Object resultObj=obj.getValue();
assertNotNull(resultObj);
assertTrue(resultObj instanceof Double);
Double doubleResult=(Double)resultObj;
assertTrue(doubleResult.doubleValue() == val.doubleValue());
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testCreateCorbaBoolean(){
Boolean val=Boolean.FALSE;
CorbaPrimitiveHandler obj=new CorbaPrimitiveHandler(new QName("boolean"),CorbaConstants.NT_CORBA_BOOLEAN,orb.get_primitive_tc(TCKind.tk_boolean),null);
assertNotNull(obj);
obj.setValueFromData(val.toString());
String result=obj.getDataFromValue();
assertTrue(val.toString().equals(result));
obj.setValue(val);
Object resultObj=obj.getValue();
assertNotNull(resultObj);
assertTrue(resultObj instanceof Boolean);
Boolean boolResult=(Boolean)resultObj;
assertTrue(boolResult.booleanValue() == val.booleanValue());
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testCreateCorbaULong(){
Integer val=new Integer(654321);
CorbaPrimitiveHandler obj=new CorbaPrimitiveHandler(new QName("ulong"),CorbaConstants.NT_CORBA_ULONG,orb.get_primitive_tc(TCKind.tk_ulong),null);
assertNotNull(obj);
obj.setValueFromData(val.toString());
String result=obj.getDataFromValue();
assertTrue(val.toString().equals(result));
obj.setValue(val);
Object resultObj=obj.getValue();
assertNotNull(resultObj);
assertTrue(resultObj instanceof Integer);
Integer ulongResult=(Integer)resultObj;
assertTrue(ulongResult.intValue() == val.intValue());
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testCreateCorbaFloat(){
Float val=new Float(1234.56);
CorbaPrimitiveHandler obj=new CorbaPrimitiveHandler(new QName("float"),CorbaConstants.NT_CORBA_FLOAT,orb.get_primitive_tc(TCKind.tk_float),null);
assertNotNull(obj);
obj.setValueFromData(val.toString());
String result=obj.getDataFromValue();
assertTrue(val.toString().equals(result));
obj.setValue(val);
Object resultObj=obj.getValue();
assertNotNull(resultObj);
assertTrue(resultObj instanceof Float);
Float floatResult=(Float)resultObj;
assertTrue(floatResult.floatValue() == val.floatValue());
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testCreateCorbaOctet(){
Byte val=new Byte((byte)100);
CorbaPrimitiveHandler obj=new CorbaPrimitiveHandler(new QName("octet"),CorbaConstants.NT_CORBA_OCTET,orb.get_primitive_tc(TCKind.tk_octet),null);
assertNotNull(obj);
obj.setValueFromData(val.toString());
String result=obj.getDataFromValue();
assertTrue(val.toString().equals(result));
obj.setValue(val);
Object resultObj=obj.getValue();
assertNotNull(resultObj);
assertTrue(resultObj instanceof Byte);
Byte byteResult=(Byte)resultObj;
assertTrue(byteResult.byteValue() == val.byteValue());
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testCreateCorbaShort(){
Short val=new Short((short)1234);
CorbaPrimitiveHandler obj=new CorbaPrimitiveHandler(new QName("short"),CorbaConstants.NT_CORBA_SHORT,orb.get_primitive_tc(TCKind.tk_short),null);
assertNotNull(obj);
obj.setValueFromData(val.toString());
String result=obj.getDataFromValue();
assertTrue(val.toString().equals(result));
obj.setValue(val);
Object resultObj=obj.getValue();
assertNotNull(resultObj);
assertTrue(resultObj instanceof Short);
Short shortResult=(Short)resultObj;
assertTrue(shortResult.shortValue() == val.shortValue());
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testCreateCorbaLong(){
Integer val=new Integer(123456);
CorbaPrimitiveHandler obj=new CorbaPrimitiveHandler(new QName("long"),CorbaConstants.NT_CORBA_LONG,orb.get_primitive_tc(TCKind.tk_long),null);
assertNotNull(obj);
obj.setValueFromData(val.toString());
String result=obj.getDataFromValue();
assertTrue(val.toString().equals(result));
obj.setValue(val);
Object resultObj=obj.getValue();
assertNotNull(resultObj);
assertTrue(resultObj instanceof Integer);
Integer longResult=(Integer)resultObj;
assertTrue(longResult.intValue() == val.intValue());
}
Class: org.apache.cxf.binding.corba.types.CorbaSequenceHandlerTest IterativeVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testCorbaSequenceHandler(){
objName=new QName("object");
objIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"sequenceType",CorbaConstants.NP_WSDL_CORBA);
objTypeCode=orb.create_sequence_tc(5,orb.get_primitive_tc(TCKind.tk_long));
Sequence sequenceType=new Sequence();
sequenceType.setName("sequenceType");
sequenceType.setElemtype(CorbaConstants.NT_CORBA_LONG);
sequenceType.setBound(5);
sequenceType.setRepositoryID("IDL:SequenceType:1.0");
obj=new CorbaSequenceHandler(objName,objIdlType,objTypeCode,sequenceType);
assertNotNull(obj);
int sequenceData[]={2,4,6,8,10};
for (int i=0; i < sequenceData.length; ++i) {
QName elName=new QName("item");
QName elIdlType=CorbaConstants.NT_CORBA_LONG;
TypeCode elTC=orb.get_primitive_tc(TCKind.tk_long);
CorbaPrimitiveHandler el=new CorbaPrimitiveHandler(elName,elIdlType,elTC,null);
el.setValue(Integer.valueOf(sequenceData[i]));
obj.addElement(el);
}
QName nameResult=obj.getName();
assertNotNull(nameResult);
assertTrue(objName.equals(nameResult));
QName idlTypeResult=obj.getIdlType();
assertNotNull(idlTypeResult);
assertTrue(idlTypeResult.equals(objIdlType));
TypeCode tcResult=obj.getTypeCode();
assertNotNull(tcResult);
assertTrue(tcResult.kind().value() == objTypeCode.kind().value());
Object objDefResult=obj.getType();
assertNotNull(objDefResult);
assertTrue(objDefResult instanceof Sequence);
int countResult=obj.getNumberOfElements();
for (int i=0; i < countResult; ++i) {
CorbaObjectHandler elResult=obj.getElement(i);
assertNotNull(elResult);
}
}
Class: org.apache.cxf.binding.corba.types.CorbaStructHandlerTest BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testCorbaStructHandler(){
Struct structType=new Struct();
structType.setName("TestStruct");
structType.setRepositoryID("IDL:TestStruct:1.0");
MemberType member0=new MemberType();
member0.setIdltype(CorbaConstants.NT_CORBA_LONG);
member0.setName("member0");
MemberType member1=new MemberType();
member1.setIdltype(CorbaConstants.NT_CORBA_STRING);
member1.setName("member1");
QName structName=new QName("TestStruct");
QName structIdlType=new QName(CorbaConstants.NU_WSDL_CORBA,"testStruct",CorbaConstants.NP_WSDL_CORBA);
StructMember[] structMembers=new StructMember[2];
structMembers[0]=new StructMember("member0",orb.get_primitive_tc(TCKind.tk_long),null);
structMembers[1]=new StructMember("member1",orb.get_primitive_tc(TCKind.tk_string),null);
TypeCode structTC=orb.create_struct_tc(structType.getRepositoryID(),structType.getName(),structMembers);
CorbaStructHandler obj=new CorbaStructHandler(structName,structIdlType,structTC,structType);
assertNotNull(obj);
CorbaPrimitiveHandler objMember0=new CorbaPrimitiveHandler(new QName(member0.getName()),member0.getIdltype(),orb.get_primitive_tc(TCKind.tk_long),null);
assertNotNull(objMember0);
obj.addMember(objMember0);
CorbaPrimitiveHandler objMember1=new CorbaPrimitiveHandler(new QName(member1.getName()),member1.getIdltype(),orb.get_primitive_tc(TCKind.tk_string),null);
assertNotNull(objMember1);
obj.addMember(objMember1);
int memberSize=obj.getMembers().size();
assertTrue(memberSize == 2);
QName nameResult=obj.getName();
assertTrue(structName.equals(nameResult));
QName idlTypeResult=obj.getIdlType();
assertTrue(structIdlType.equals(idlTypeResult));
CorbaObjectHandler member0Result=obj.getMemberByName("member0");
assertNotNull(member0Result);
assertTrue(member0Result.getName().equals(objMember0.getName()));
CorbaObjectHandler member1Result=obj.getMember(1);
assertNotNull(member1Result);
assertTrue(member1Result.getName().equals(objMember1.getName()));
}
Class: org.apache.cxf.binding.corba.utils.ContextUtilsTest InternalCallVerifier EqualityVerifier
@Test public void testIsRequestor() throws Exception {
Message message=new MessageImpl();
message.put("org.apache.cxf.client","org.apache.cxf.client");
assertEquals(ContextUtils.isRequestor(message),true);
}
InternalCallVerifier EqualityVerifier
@Test public void testIsOutbound() throws Exception {
Message message=new MessageImpl();
Exchange exchange=new ExchangeImpl();
exchange.setOutMessage(message);
message.setExchange(exchange);
assertEquals(ContextUtils.isOutbound(message),true);
}
Class: org.apache.cxf.binding.object.LocalServerRegistrationTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testServer() throws Exception {
BindingFactoryManager bfm=getBus().getExtension(BindingFactoryManager.class);
ObjectBindingFactory obj=(ObjectBindingFactory)bfm.getBindingFactory(ObjectBindingFactory.BINDING_ID);
obj.setAutoRegisterLocalEndpoint(true);
ServerFactoryBean sfb=new ServerFactoryBean();
sfb.setServiceClass(EchoImpl.class);
sfb.setAddress("http://localhost:" + TestUtil.getPortNumber(LocalServerRegistrationTest.class) + "/echo");
Server server=sfb.create();
List content=new ArrayList();
content.add("Hello");
ServiceInfo serviceInfo=server.getEndpoint().getEndpointInfo().getService();
BindingInfo bi=serviceInfo.getBindings().iterator().next();
BindingOperationInfo bop=bi.getOperations().iterator().next();
assertNotNull(bop.getOperationInfo());
MessageImpl m=new MessageImpl();
m.setContent(List.class,content);
ExchangeImpl ex=new ExchangeImpl();
ex.setInMessage(m);
ex.put(BindingOperationInfo.class,bop);
Conduit c=getLocalConduit("local://" + server);
ex.setConduit(c);
new ObjectDispatchOutInterceptor().handleMessage(m);
c.setMessageObserver(new MessageObserver(){
public void onMessage( Message message){
response=message;
}
}
);
c.prepare(m);
c.close(m);
Thread.sleep(1000);
assertNotNull(response);
List> content2=CastUtils.cast((List>)response.getContent(List.class));
assertNotNull(content2);
assertEquals(1,content2.size());
}
Class: org.apache.cxf.binding.object.ObjectBindingTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testClient() throws Exception {
ClientFactoryBean cfb=new ClientFactoryBean();
cfb.setBindingId(ObjectBindingFactory.BINDING_ID);
cfb.setServiceClass(EchoImpl.class);
cfb.setAddress("local://Echo");
Client client=cfb.create();
final List content=new ArrayList();
content.add("Hello");
final Destination d=getLocalDestination("local://Echo");
d.setMessageObserver(new MessageObserver(){
public void onMessage( Message inMsg){
MessageImpl outMsg=new MessageImpl();
outMsg.setContent(List.class,content);
outMsg.put(LocalConduit.DIRECT_DISPATCH,Boolean.TRUE);
inMsg.getExchange().setInMessage(outMsg);
try {
Conduit backChannel=d.getBackChannel(inMsg);
backChannel.prepare(outMsg);
backChannel.close(outMsg);
}
catch ( IOException e) {
e.printStackTrace();
}
}
}
);
Object[] res=client.invoke("echo",content.toArray());
assertNotNull(res);
assertEquals(1,res.length);
assertEquals("Hello",res[0]);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testServer() throws Exception {
ServerFactoryBean sfb=new ServerFactoryBean();
sfb.setBindingId(ObjectBindingFactory.BINDING_ID);
sfb.setServiceClass(EchoImpl.class);
sfb.setAddress("local://Echo");
Server server=sfb.create();
List content=new ArrayList();
content.add("Hello");
ServiceInfo serviceInfo=server.getEndpoint().getEndpointInfo().getService();
BindingInfo bi=serviceInfo.getBindings().iterator().next();
BindingOperationInfo bop=bi.getOperations().iterator().next();
assertNotNull(bop.getOperationInfo());
MessageImpl m=new MessageImpl();
m.setContent(List.class,content);
ExchangeImpl ex=new ExchangeImpl();
ex.setInMessage(m);
ex.put(BindingOperationInfo.class,bop);
Conduit c=getLocalConduit("local://Echo");
ex.setConduit(c);
new ObjectDispatchOutInterceptor().handleMessage(m);
ex.setConduit(c);
c.setMessageObserver(new MessageObserver(){
public void onMessage( Message message){
response=message;
}
}
);
c.prepare(m);
c.close(m);
Thread.sleep(1000);
assertNotNull(response);
List> content2=CastUtils.cast((List>)response.getContent(List.class));
assertNotNull(content2);
assertEquals(1,content2.size());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testClientServer() throws Exception {
ClientFactoryBean cfb=new ClientFactoryBean();
cfb.setBindingId(ObjectBindingFactory.BINDING_ID);
cfb.setServiceClass(EchoImpl.class);
cfb.setAddress("local://Echo");
Client client=cfb.create();
ServerFactoryBean sfb=new ServerFactoryBean();
sfb.setBindingId(ObjectBindingFactory.BINDING_ID);
sfb.setServiceClass(EchoImpl.class);
sfb.setAddress("local://Echo");
sfb.create();
Object[] res=client.invoke("echo",new Object[]{"Hello"});
assertNotNull(res);
assertEquals(1,res.length);
assertEquals("Hello",res[0]);
}
Class: org.apache.cxf.binding.soap.MustUnderstandInterceptorTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testHandleMessageSucc() throws Exception {
prepareSoapMessage("test-soap-header.xml");
dsi.getUnderstoodHeaders().add(RESERVATION);
dsi.getUnderstoodHeaders().add(PASSENGER);
soapMessage.getInterceptorChain().doIntercept(soapMessage);
assertEquals("DummaySoapInterceptor getRoles has been called!",true,dsi.isCalledGetRoles());
assertEquals("DummaySoapInterceptor getUnderstood has been called!",true,dsi.isCalledGetUnderstood());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testHandleMessageWithSoapHeader11Param() throws Exception {
prepareSoapMessage("test-soap-header.xml");
dsi.getUnderstoodHeaders().add(RESERVATION);
ServiceInfo serviceInfo=getMockedServiceModel(getClass().getResource("test-soap-header.wsdl").toString());
BindingInfo binding=serviceInfo.getBinding(new QName("http://org.apache.cxf/headers","headerTesterSOAPBinding"));
BindingOperationInfo bop=binding.getOperation(new QName("http://org.apache.cxf/headers","inHeader"));
soapMessage.getExchange().put(BindingOperationInfo.class,bop);
soapMessage.getInterceptorChain().doIntercept(soapMessage);
assertEquals("DummaySoapInterceptor getRoles has been called!",true,dsi.isCalledGetRoles());
assertEquals("DummaySoapInterceptor getUnderstood has been called!",true,dsi.isCalledGetUnderstood());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testHandleMessageWithSoapHeader12Param() throws Exception {
prepareSoapMessage("test-soap-12-header.xml");
dsi.getUnderstoodHeaders().add(RESERVATION);
ServiceInfo serviceInfo=getMockedServiceModel(getClass().getResource("test-soap-12-header.wsdl").toString());
BindingInfo binding=serviceInfo.getBinding(new QName("http://org.apache.cxf/headers","headerTesterSOAPBinding"));
BindingOperationInfo bop=binding.getOperation(new QName("http://org.apache.cxf/headers","inHeader"));
soapMessage.getExchange().put(BindingOperationInfo.class,bop);
soapMessage.getInterceptorChain().doIntercept(soapMessage);
assertEquals("DummaySoapInterceptor getRoles has been called!",true,dsi.isCalledGetRoles());
assertEquals("DummaySoapInterceptor getUnderstood has been called!",true,dsi.isCalledGetUnderstood());
}
APIUtilityVerifier BranchVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testHandleMessageFail() throws Exception {
prepareSoapMessage("test-soap-header.xml");
dsi.getUnderstoodHeaders().add(RESERVATION);
soapMessage.getInterceptorChain().doIntercept(soapMessage);
assertEquals("DummaySoapInterceptor getRoles has been called!",true,dsi.isCalledGetRoles());
assertEquals("DummaySoapInterceptor getUnderstood has been called!",true,dsi.isCalledGetUnderstood());
Set ie=CastUtils.cast((Set>)soapMessage.get(MustUnderstandInterceptor.UNKNOWNS));
if (ie == null) {
fail("InBound unknowns missing! Exception should be Can't understands QNames: " + PASSENGER);
}
else {
assertTrue(ie.contains(PASSENGER));
}
}
Class: org.apache.cxf.binding.soap.RPCInInterceptorTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testInterceptorRPCLitOutbound() throws Exception {
RPCInInterceptor interceptor=new RPCInInterceptor();
soapMessage.setContent(XMLStreamReader.class,XMLInputFactory.newInstance().createXMLStreamReader(getTestStream(getClass(),"/rpc-resp.xml")));
soapMessage.put(Message.REQUESTOR_ROLE,Boolean.TRUE);
interceptor.handleMessage(soapMessage);
List> parameters=soapMessage.getContent(List.class);
assertEquals(1,parameters.size());
Object obj=parameters.get(0);
assertTrue(obj instanceof MyComplexStruct);
MyComplexStruct s=(MyComplexStruct)obj;
assertEquals("elem1",s.getElem1());
assertEquals("elem2",s.getElem2());
assertEquals(45,s.getElem3());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testInterceptorRPCLitInbound() throws Exception {
RPCInInterceptor interceptor=new RPCInInterceptor();
soapMessage.setContent(XMLStreamReader.class,XMLInputFactory.newInstance().createXMLStreamReader(getTestStream(getClass(),"/rpc-req.xml")));
interceptor.handleMessage(soapMessage);
List> parameters=soapMessage.getContent(List.class);
assertEquals(2,parameters.size());
Object obj=parameters.get(1);
assertTrue(obj instanceof MyComplexStruct);
MyComplexStruct s=(MyComplexStruct)obj;
assertEquals("elem1",s.getElem1());
assertEquals("elem2",s.getElem2());
assertEquals(45,s.getElem3());
}
Class: org.apache.cxf.binding.soap.RPCOutInterceptorTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testWriteInbound() throws Exception {
RPCOutInterceptor interceptor=new RPCOutInterceptor();
soapMessage.setContent(XMLStreamWriter.class,XMLOutputFactory.newInstance().createXMLStreamWriter(baos));
interceptor.handleMessage(soapMessage);
assertNull(soapMessage.getContent(Exception.class));
soapMessage.getContent(XMLStreamWriter.class).flush();
baos.flush();
ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
XMLStreamReader xr=StaxUtils.createXMLStreamReader(bais);
DepthXMLStreamReader reader=new DepthXMLStreamReader(xr);
StaxUtils.toNextElement(reader);
assertEquals(new QName("http://apache.org/hello_world_rpclit","sendReceiveDataResponse"),reader.getName());
StaxUtils.nextEvent(reader);
StaxUtils.toNextElement(reader);
assertEquals(new QName(null,"out"),reader.getName());
StaxUtils.nextEvent(reader);
StaxUtils.toNextElement(reader);
assertEquals(new QName("http://apache.org/hello_world_rpclit/types","elem1"),reader.getName());
StaxUtils.nextEvent(reader);
StaxUtils.toNextText(reader);
assertEquals("elem1",reader.getText());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testWriteOutbound() throws Exception {
RPCOutInterceptor interceptor=new RPCOutInterceptor();
soapMessage.setContent(XMLStreamWriter.class,XMLOutputFactory.newInstance().createXMLStreamWriter(baos));
soapMessage.put(Message.REQUESTOR_ROLE,Boolean.TRUE);
interceptor.handleMessage(soapMessage);
assertNull(soapMessage.getContent(Exception.class));
soapMessage.getContent(XMLStreamWriter.class).flush();
baos.flush();
ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
XMLStreamReader xr=StaxUtils.createXMLStreamReader(bais);
DepthXMLStreamReader reader=new DepthXMLStreamReader(xr);
StaxUtils.toNextElement(reader);
assertEquals(new QName("http://apache.org/hello_world_rpclit","sendReceiveData"),reader.getName());
StaxUtils.nextEvent(reader);
StaxUtils.toNextElement(reader);
assertEquals(new QName(null,"in"),reader.getName());
StaxUtils.toNextText(reader);
assertEquals("elem1",reader.getText());
}
Class: org.apache.cxf.binding.soap.ServiceModelUtilTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetSchema() throws Exception {
BindingInfo bindingInfo=null;
bindingInfo=serviceInfo.getBindings().iterator().next();
QName name=new QName(serviceInfo.getName().getNamespaceURI(),"inHeader");
BindingOperationInfo inHeader=bindingInfo.getOperation(name);
BindingMessageInfo input=inHeader.getInput();
assertNotNull(input);
assertEquals(input.getMessageInfo().getName().getLocalPart(),"inHeaderRequest");
assertEquals(input.getMessageInfo().getName().getNamespaceURI(),"http://org.apache.cxf/headers");
assertEquals(input.getMessageInfo().getMessageParts().size(),2);
assertTrue(input.getMessageInfo().getMessageParts().get(0).isElement());
assertEquals(input.getMessageInfo().getMessageParts().get(0).getElementQName().getLocalPart(),"inHeader");
assertEquals(input.getMessageInfo().getMessageParts().get(0).getElementQName().getNamespaceURI(),"http://org.apache.cxf/headers");
assertTrue(input.getMessageInfo().getMessageParts().get(0).isElement());
assertEquals(input.getMessageInfo().getMessageParts().get(1).getElementQName().getLocalPart(),"passenger");
assertEquals(input.getMessageInfo().getMessageParts().get(1).getElementQName().getNamespaceURI(),"http://mycompany.example.com/employees");
assertTrue(input.getMessageInfo().getMessageParts().get(1).isElement());
MessagePartInfo messagePartInfo=input.getMessageInfo().getMessageParts().get(0);
SchemaInfo schemaInfo=ServiceModelUtil.getSchema(serviceInfo,messagePartInfo);
assertEquals(schemaInfo.getNamespaceURI(),"http://org.apache.cxf/headers");
messagePartInfo=input.getMessageInfo().getMessageParts().get(1);
schemaInfo=ServiceModelUtil.getSchema(serviceInfo,messagePartInfo);
assertEquals(schemaInfo.getNamespaceURI(),"http://mycompany.example.com/employees");
}
Class: org.apache.cxf.binding.soap.SoapActionInterceptorTest BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSoapAction() throws Exception {
SoapPreProtocolOutInterceptor i=new SoapPreProtocolOutInterceptor();
Message message=new MessageImpl();
message.setExchange(new ExchangeImpl());
message.getExchange().setOutMessage(message);
SoapBinding sb=new SoapBinding(null);
message=sb.createMessage(message);
assertNotNull(message);
assertTrue(message instanceof SoapMessage);
SoapMessage soapMessage=(SoapMessage)message;
soapMessage.put(Message.REQUESTOR_ROLE,Boolean.TRUE);
assertEquals(Soap11.getInstance(),soapMessage.getVersion());
(new SoapPreProtocolOutInterceptor()).handleMessage(soapMessage);
Map> reqHeaders=CastUtils.cast((Map,?>)soapMessage.get(Message.PROTOCOL_HEADERS));
assertNotNull(reqHeaders);
assertEquals("\"\"",reqHeaders.get(SoapBindingConstants.SOAP_ACTION).get(0));
sb.setSoapVersion(Soap12.getInstance());
soapMessage.clear();
soapMessage=(SoapMessage)sb.createMessage(soapMessage);
soapMessage.put(Message.REQUESTOR_ROLE,Boolean.TRUE);
i.handleMessage(soapMessage);
String ct=(String)soapMessage.get(Message.CONTENT_TYPE);
assertEquals("application/soap+xml",ct);
BindingOperationInfo bop=createBindingOperation();
soapMessage.getExchange().put(BindingOperationInfo.class,bop);
SoapOperationInfo soapInfo=new SoapOperationInfo();
soapInfo.setAction("foo");
bop.addExtensor(soapInfo);
i.handleMessage(soapMessage);
ct=(String)soapMessage.get(Message.CONTENT_TYPE);
assertEquals("application/soap+xml; action=\"foo\"",ct);
}
Class: org.apache.cxf.binding.soap.SoapBindingFactoryTest BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testFactory() throws Exception {
Definition d=createDefinition("/wsdl_soap/hello_world.wsdl");
Bus bus=getMockBus();
BindingFactoryManager bfm=getBindingFactoryManager(WSDLConstants.NS_SOAP11,bus);
bus.getExtension(BindingFactoryManager.class);
expectLastCall().andReturn(bfm).anyTimes();
DestinationFactoryManager dfm=control.createMock(DestinationFactoryManager.class);
expect(bus.getExtension(DestinationFactoryManager.class)).andStubReturn(dfm);
control.replay();
WSDLServiceBuilder builder=new WSDLServiceBuilder(bus);
ServiceInfo serviceInfo=builder.buildServices(d,new QName("http://apache.org/hello_world_soap_http","SOAPService")).get(0);
BindingInfo bi=serviceInfo.getBindings().iterator().next();
assertTrue(bi instanceof SoapBindingInfo);
SoapBindingInfo sbi=(SoapBindingInfo)bi;
assertEquals("document",sbi.getStyle());
assertTrue(WSDLConstants.NS_SOAP11_HTTP_TRANSPORT.equalsIgnoreCase(sbi.getTransportURI()));
assertTrue(sbi.getSoapVersion() instanceof Soap11);
BindingOperationInfo boi=sbi.getOperation(new QName("http://apache.org/hello_world_soap_http","sayHi"));
SoapOperationInfo sboi=boi.getExtensor(SoapOperationInfo.class);
assertNotNull(sboi);
assertEquals("document",sboi.getStyle());
assertEquals("",sboi.getAction());
BindingMessageInfo input=boi.getInput();
SoapBodyInfo bodyInfo=input.getExtensor(SoapBodyInfo.class);
assertEquals("literal",bodyInfo.getUse());
List parts=bodyInfo.getParts();
assertNotNull(parts);
assertEquals(1,parts.size());
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSoap12Factory() throws Exception {
Definition d=createDefinition("/wsdl_soap/hello_world_soap12.wsdl");
Bus bus=getMockBus();
BindingFactoryManager bfm=getBindingFactoryManager(WSDLConstants.NS_SOAP12,bus);
expect(bus.getExtension(BindingFactoryManager.class)).andReturn(bfm);
DestinationFactoryManager dfm=control.createMock(DestinationFactoryManager.class);
expect(bus.getExtension(DestinationFactoryManager.class)).andStubReturn(dfm);
control.replay();
WSDLServiceBuilder builder=new WSDLServiceBuilder(bus);
ServiceInfo serviceInfo=builder.buildServices(d,new QName("http://apache.org/hello_world_soap12_http","SOAPService")).get(0);
BindingInfo bi=serviceInfo.getBindings().iterator().next();
assertTrue(bi instanceof SoapBindingInfo);
SoapBindingInfo sbi=(SoapBindingInfo)bi;
assertEquals("document",sbi.getStyle());
assertEquals(WSDLConstants.NS_SOAP_HTTP_TRANSPORT,sbi.getTransportURI());
assertTrue(sbi.getSoapVersion() instanceof Soap12);
BindingOperationInfo boi=sbi.getOperation(new QName("http://apache.org/hello_world_soap12_http","sayHi"));
SoapOperationInfo sboi=boi.getExtensor(SoapOperationInfo.class);
assertNotNull(sboi);
assertEquals("document",sboi.getStyle());
assertEquals("sayHiAction",sboi.getAction());
BindingMessageInfo input=boi.getInput();
SoapBodyInfo bodyInfo=input.getExtensor(SoapBodyInfo.class);
assertEquals("literal",bodyInfo.getUse());
List parts=bodyInfo.getParts();
assertNotNull(parts);
assertEquals(1,parts.size());
boi=sbi.getOperation(new QName("http://apache.org/hello_world_soap12_http","pingMe"));
sboi=boi.getExtensor(SoapOperationInfo.class);
assertNotNull(sboi);
assertEquals("document",sboi.getStyle());
assertEquals("",sboi.getAction());
Collection faults=boi.getFaults();
assertEquals(1,faults.size());
BindingFaultInfo faultInfo=boi.getFault(new QName("http://apache.org/hello_world_soap12_http","pingMeFault"));
assertNotNull(faultInfo);
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testNoBodyParts() throws Exception {
Definition d=createDefinition("/wsdl_soap/no_body_parts.wsdl");
Bus bus=getMockBus();
BindingFactoryManager bfm=getBindingFactoryManager(WSDLConstants.NS_SOAP11,bus);
bus.getExtension(BindingFactoryManager.class);
expectLastCall().andReturn(bfm).anyTimes();
DestinationFactoryManager dfm=control.createMock(DestinationFactoryManager.class);
expect(bus.getExtension(DestinationFactoryManager.class)).andStubReturn(dfm);
control.replay();
WSDLServiceBuilder builder=new WSDLServiceBuilder(bus);
ServiceInfo serviceInfo=builder.buildServices(d,new QName("urn:org:apache:cxf:no_body_parts/wsdl","NoBodyParts")).get(0);
BindingInfo bi=serviceInfo.getBindings().iterator().next();
assertTrue(bi instanceof SoapBindingInfo);
SoapBindingInfo sbi=(SoapBindingInfo)bi;
assertEquals("document",sbi.getStyle());
assertTrue(WSDLConstants.NS_SOAP11_HTTP_TRANSPORT.equalsIgnoreCase(sbi.getTransportURI()));
assertTrue(sbi.getSoapVersion() instanceof Soap11);
BindingOperationInfo boi=sbi.getOperation(new QName("urn:org:apache:cxf:no_body_parts/wsdl","operation1"));
assertNotNull(boi);
SoapOperationInfo sboi=boi.getExtensor(SoapOperationInfo.class);
assertNotNull(sboi);
assertNull(sboi.getStyle());
assertEquals("",sboi.getAction());
BindingMessageInfo input=boi.getInput();
SoapBodyInfo bodyInfo=input.getExtensor(SoapBodyInfo.class);
assertNull(bodyInfo.getUse());
List parts=bodyInfo.getParts();
assertNotNull(parts);
assertEquals(0,parts.size());
}
Class: org.apache.cxf.binding.soap.SoapBindingTest BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCreateMessage() throws Exception {
Message message=new MessageImpl();
SoapBinding sb=new SoapBinding(null);
message=sb.createMessage(message);
assertNotNull(message);
assertTrue(message instanceof SoapMessage);
SoapMessage soapMessage=(SoapMessage)message;
assertEquals(Soap11.getInstance(),soapMessage.getVersion());
assertEquals("text/xml",soapMessage.get(Message.CONTENT_TYPE));
soapMessage.remove(Message.CONTENT_TYPE);
sb.setSoapVersion(Soap12.getInstance());
soapMessage=(SoapMessage)sb.createMessage(soapMessage);
assertEquals(Soap12.getInstance(),soapMessage.getVersion());
assertEquals("application/soap+xml",soapMessage.get(Message.CONTENT_TYPE));
}
Class: org.apache.cxf.binding.soap.interceptor.ReadHeadersInterceptorTest InternalCallVerifier NullVerifier
@Test public void testNotAddNSContext() throws Exception {
SoapMessage message=setUpMessage();
interceptor.handleMessage(message);
Map nsc=CastUtils.cast((Map,?>)message.get("soap.body.ns.context"));
assertNull(nsc);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testAddNSContext() throws Exception {
SoapMessage message=setUpMessage();
message.put("org.apache.cxf.binding.soap.addNamespaceContext","true");
interceptor.handleMessage(message);
Map nsc=CastUtils.cast((Map,?>)message.get("soap.body.ns.context"));
assertNotNull(nsc);
assertEquals("http://www.w3.org/2001/XMLSchema-instance",nsc.get("xsi"));
assertEquals("http://www.w3.org/2001/XMLSchema",nsc.get("xs"));
assertEquals("tmp:bar",nsc.get("bar"));
}
Class: org.apache.cxf.binding.soap.interceptor.SoapFaultSerializerTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCXF4181() throws Exception {
SoapMessage m=new SoapMessage(new MessageImpl());
m.put(Message.HTTP_REQUEST_METHOD,"POST");
m.setVersion(Soap12.getInstance());
XMLStreamReader reader=StaxUtils.createXMLStreamReader(this.getClass().getResourceAsStream("cxf4181.xml"));
m.setContent(XMLStreamReader.class,reader);
new SAAJPreInInterceptor().handleMessage(m);
new ReadHeadersInterceptor(null).handleMessage(m);
new StartBodyInterceptor().handleMessage(m);
new SAAJInInterceptor().handleMessage(m);
new Soap12FaultInInterceptor().handleMessage(m);
Node nd=m.getContent(Node.class);
SOAPPart part=(SOAPPart)nd;
assertEquals("S",part.getEnvelope().getPrefix());
assertEquals("S2",part.getEnvelope().getHeader().getPrefix());
assertEquals("S3",part.getEnvelope().getBody().getPrefix());
SOAPFault fault=part.getEnvelope().getBody().getFault();
assertEquals("S",fault.getPrefix());
assertEquals("Authentication Failure",fault.getFaultString());
SoapFault fault2=(SoapFault)m.getContent(Exception.class);
assertNotNull(fault2);
assertEquals(Soap12.getInstance().getSender(),fault2.getFaultCode());
assertEquals(new QName("http://schemas.xmlsoap.org/ws/2005/02/trust","FailedAuthentication"),fault2.getSubCode());
Element el=part.getEnvelope().getBody();
nd=el.getFirstChild();
int count=0;
while (nd != null) {
if (nd instanceof Element) {
count++;
}
nd=nd.getNextSibling();
}
assertEquals(1,count);
m=new SoapMessage(new MessageImpl());
m.setVersion(Soap12.getInstance());
reader=StaxUtils.createXMLStreamReader(this.getClass().getResourceAsStream("cxf4181.xml"));
m.setContent(XMLStreamReader.class,reader);
m.put(Message.HTTP_REQUEST_METHOD,"POST");
new ReadHeadersInterceptor(null).handleMessage(m);
new StartBodyInterceptor().handleMessage(m);
new Soap12FaultInInterceptor().handleMessage(m);
nd=m.getContent(Node.class);
fault2=(SoapFault)m.getContent(Exception.class);
assertNotNull(fault2);
assertEquals(Soap12.getInstance().getSender(),fault2.getFaultCode());
assertEquals(new QName("http://schemas.xmlsoap.org/ws/2005/02/trust","FailedAuthentication"),fault2.getSubCode());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSoap12WithMultipleSubCodesOut() throws Exception {
String faultString="Hadrian caused this Fault!";
SoapFault fault=new SoapFault(faultString,Soap12.getInstance().getSender());
fault.addSubCode(new QName("http://cxf.apache.org/soap/fault","invalidsoap","cxffaultcode"));
fault.addSubCode(new QName("http://cxf.apache.org/soap/fault2","invalidsoap2","cxffaultcode2"));
SoapMessage m=new SoapMessage(new MessageImpl());
m.setVersion(Soap12.getInstance());
m.setContent(Exception.class,fault);
ByteArrayOutputStream out=new ByteArrayOutputStream();
XMLStreamWriter writer=StaxUtils.createXMLStreamWriter(out);
writer.writeStartDocument();
writer.writeStartElement("Body");
m.setContent(XMLStreamWriter.class,writer);
Soap12FaultOutInterceptorInternal.INSTANCE.handleMessage(m);
writer.writeEndElement();
writer.writeEndDocument();
writer.close();
Document faultDoc=StaxUtils.read(new ByteArrayInputStream(out.toByteArray()));
assertValid("//soap12env:Fault/soap12env:Code/soap12env:Value[text()='ns1:Sender']",faultDoc);
assertValid("//soap12env:Fault/soap12env:Code/soap12env:Subcode/" + "soap12env:Value[text()='ns2:invalidsoap']",faultDoc);
assertValid("//soap12env:Fault/soap12env:Code/soap12env:Subcode/soap12env:Subcode/" + "soap12env:Value[text()='ns2:invalidsoap2']",faultDoc);
assertValid("//soap12env:Fault/soap12env:Reason/soap12env:Text[@xml:lang='en']",faultDoc);
assertValid("//soap12env:Fault/soap12env:Reason/soap12env:Text[text()='" + faultString + "']",faultDoc);
XMLStreamReader reader=StaxUtils.createXMLStreamReader(new ByteArrayInputStream(out.toByteArray()));
m.setContent(XMLStreamReader.class,reader);
reader.nextTag();
Soap12FaultInInterceptor inInterceptor=new Soap12FaultInInterceptor();
inInterceptor.handleMessage(m);
SoapFault fault2=(SoapFault)m.getContent(Exception.class);
assertNotNull(fault2);
assertEquals(Soap12.getInstance().getSender(),fault2.getFaultCode());
assertEquals(fault.getMessage(),fault2.getMessage());
assertEquals(fault.getSubCodes(),fault2.getSubCodes());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSoap11Out() throws Exception {
String faultString="Hadrian caused this Fault!";
SoapFault fault=new SoapFault(faultString,Soap11.getInstance().getSender());
SoapMessage m=new SoapMessage(new MessageImpl());
m.setExchange(new ExchangeImpl());
m.setContent(Exception.class,fault);
ByteArrayOutputStream out=new ByteArrayOutputStream();
XMLStreamWriter writer=StaxUtils.createXMLStreamWriter(out);
writer.writeStartDocument();
writer.writeStartElement("Body");
m.setContent(XMLStreamWriter.class,writer);
Soap11FaultOutInterceptorInternal.INSTANCE.handleMessage(m);
writer.writeEndElement();
writer.writeEndDocument();
writer.close();
Document faultDoc=StaxUtils.read(new ByteArrayInputStream(out.toByteArray()));
assertValid("//s:Fault/faultcode[text()='ns1:Client']",faultDoc);
assertValid("//s:Fault/faultstring[text()='" + faultString + "']",faultDoc);
XMLStreamReader reader=StaxUtils.createXMLStreamReader(new ByteArrayInputStream(out.toByteArray()));
m.setContent(XMLStreamReader.class,reader);
reader.nextTag();
Soap11FaultInInterceptor inInterceptor=new Soap11FaultInInterceptor();
inInterceptor.handleMessage(m);
SoapFault fault2=(SoapFault)m.getContent(Exception.class);
assertNotNull(fault2);
assertEquals(fault.getMessage(),fault2.getMessage());
assertEquals(Soap11.getInstance().getSender(),fault2.getFaultCode());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCXF1864() throws Exception {
SoapMessage m=new SoapMessage(new MessageImpl());
m.setVersion(Soap12.getInstance());
XMLStreamReader reader=StaxUtils.createXMLStreamReader(this.getClass().getResourceAsStream("cxf1864.xml"));
m.setContent(XMLStreamReader.class,reader);
reader.nextTag();
Soap12FaultInInterceptor inInterceptor=new Soap12FaultInInterceptor();
inInterceptor.handleMessage(m);
SoapFault fault2=(SoapFault)m.getContent(Exception.class);
assertNotNull(fault2);
assertEquals(Soap12.getInstance().getReceiver(),fault2.getFaultCode());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCXF5493() throws Exception {
SoapMessage m=new SoapMessage(new MessageImpl());
m.setVersion(Soap11.getInstance());
XMLStreamReader reader=StaxUtils.createXMLStreamReader(this.getClass().getResourceAsStream("cxf5493.xml"));
m.setContent(XMLStreamReader.class,reader);
reader.nextTag();
reader.nextTag();
reader.nextTag();
Soap11FaultInInterceptor inInterceptor=new Soap11FaultInInterceptor();
inInterceptor.handleMessage(m);
SoapFault fault2=(SoapFault)m.getContent(Exception.class);
assertNotNull(fault2);
assertEquals(Soap11.getInstance().getReceiver(),fault2.getFaultCode());
assertEquals("some text containing a xml tag ",fault2.getMessage());
m=new SoapMessage(new MessageImpl());
m.put(Message.HTTP_REQUEST_METHOD,"POST");
m.setVersion(Soap11.getInstance());
reader=StaxUtils.createXMLStreamReader(this.getClass().getResourceAsStream("cxf5493.xml"));
m.setContent(XMLStreamReader.class,reader);
new SAAJPreInInterceptor().handleMessage(m);
new ReadHeadersInterceptor(null).handleMessage(m);
new StartBodyInterceptor().handleMessage(m);
new SAAJInInterceptor().handleMessage(m);
new Soap11FaultInInterceptor().handleMessage(m);
fault2=(SoapFault)m.getContent(Exception.class);
assertNotNull(fault2);
assertEquals(Soap11.getInstance().getReceiver(),fault2.getFaultCode());
assertEquals("some text containing a xml tag ",fault2.getMessage());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSoap12Out() throws Exception {
String faultString="Hadrian caused this Fault!";
SoapFault fault=new SoapFault(faultString,Soap12.getInstance().getSender());
QName qname=new QName("http://cxf.apache.org/soap/fault","invalidsoap","cxffaultcode");
fault.setSubCode(qname);
SoapMessage m=new SoapMessage(new MessageImpl());
m.setVersion(Soap12.getInstance());
m.setContent(Exception.class,fault);
ByteArrayOutputStream out=new ByteArrayOutputStream();
XMLStreamWriter writer=StaxUtils.createXMLStreamWriter(out);
writer.writeStartDocument();
writer.writeStartElement("Body");
m.setContent(XMLStreamWriter.class,writer);
Soap12FaultOutInterceptorInternal.INSTANCE.handleMessage(m);
writer.writeEndElement();
writer.writeEndDocument();
writer.close();
Document faultDoc=StaxUtils.read(new ByteArrayInputStream(out.toByteArray()));
assertValid("//soap12env:Fault/soap12env:Code/soap12env:Value[text()='ns1:Sender']",faultDoc);
assertValid("//soap12env:Fault/soap12env:Code/soap12env:Subcode/" + "soap12env:Value[text()='ns2:invalidsoap']",faultDoc);
assertValid("//soap12env:Fault/soap12env:Reason/soap12env:Text[@xml:lang='en']",faultDoc);
assertValid("//soap12env:Fault/soap12env:Reason/soap12env:Text[text()='" + faultString + "']",faultDoc);
XMLStreamReader reader=StaxUtils.createXMLStreamReader(new ByteArrayInputStream(out.toByteArray()));
m.setContent(XMLStreamReader.class,reader);
reader.nextTag();
Soap12FaultInInterceptor inInterceptor=new Soap12FaultInInterceptor();
inInterceptor.handleMessage(m);
SoapFault fault2=(SoapFault)m.getContent(Exception.class);
assertNotNull(fault2);
assertEquals(Soap12.getInstance().getSender(),fault2.getFaultCode());
assertEquals(fault.getMessage(),fault2.getMessage());
assertEquals(fault.getSubCode(),fault2.getSubCode());
}
Class: org.apache.cxf.binding.soap.interceptor.SoapPreProtocolOutInterceptorTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testRequestorOutboundSoapAction() throws Exception {
SoapMessage message=setUpMessage();
interceptor.handleMessage(message);
control.verify();
Map> reqHeaders=CastUtils.cast((Map,?>)message.get(Message.PROTOCOL_HEADERS));
assertNotNull(reqHeaders);
List soapaction=reqHeaders.get("soapaction");
assertTrue(null != soapaction && soapaction.size() == 1);
assertEquals("\"http://foo/bar/SEI/opReq\"",soapaction.get(0));
}
Class: org.apache.cxf.binding.soap.jms.interceptor.SoapFaultFactoryTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void createSoap12Fault(){
SoapBinding sb=control.createMock(SoapBinding.class);
EasyMock.expect(sb.getSoapVersion()).andReturn(Soap12.getInstance());
setupJMSFault(true,SoapJMSConstants.getMismatchedSoapActionQName(),null,true);
control.replay();
SoapFaultFactory factory=new SoapFaultFactory(sb);
SoapFault fault=(SoapFault)factory.createFault(jmsFault);
assertEquals("reason",fault.getReason());
assertEquals(Soap12.getInstance().getSender(),fault.getFaultCode());
assertEquals(SoapJMSConstants.getMismatchedSoapActionQName(),fault.getSubCode());
assertNull(fault.getDetail());
assertNull(fault.getCause());
control.verify();
}
InternalCallVerifier IdentityVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void createSoap11Fault(){
SoapBinding sb=control.createMock(SoapBinding.class);
EasyMock.expect(sb.getSoapVersion()).andReturn(Soap11.getInstance());
setupJMSFault(true,SoapJMSConstants.getContentTypeMismatchQName(),null,false);
control.replay();
SoapFaultFactory factory=new SoapFaultFactory(sb);
SoapFault fault=(SoapFault)factory.createFault(jmsFault);
assertEquals("reason",fault.getReason());
assertEquals(SoapJMSConstants.getContentTypeMismatchQName(),fault.getFaultCode());
assertNull(fault.getDetail());
assertSame(jmsFault,fault.getCause());
control.verify();
}
Class: org.apache.cxf.binding.xml.interceptor.XMLFaultOutInterceptorTest InternalCallVerifier EqualityVerifier
@Test public void testFault() throws Exception {
FaultDetail detail=new FaultDetail();
detail.setMajor((short)2);
detail.setMinor((short)1);
PingMeFault fault=new PingMeFault("TEST_FAULT",detail);
XMLFault xmlFault=XMLFault.createFault(new Fault(fault));
Element el=xmlFault.getOrCreateDetail();
JAXBContext ctx=JAXBContext.newInstance(FaultDetail.class);
Marshaller m=ctx.createMarshaller();
m.marshal(detail,el);
OutputStream outputStream=new ByteArrayOutputStream();
xmlMessage.setContent(OutputStream.class,outputStream);
XMLStreamWriter writer=StaxUtils.createXMLStreamWriter(outputStream);
xmlMessage.setContent(XMLStreamWriter.class,writer);
xmlMessage.setContent(Exception.class,xmlFault);
out.handleMessage(xmlMessage);
outputStream.flush();
XMLStreamReader reader=getXMLReader();
DepthXMLStreamReader dxr=new DepthXMLStreamReader(reader);
dxr.nextTag();
StaxUtils.toNextElement(dxr);
assertEquals(XMLConstants.NS_XML_FORMAT,dxr.getNamespaceURI());
assertEquals(XMLFault.XML_FAULT_ROOT,dxr.getLocalName());
dxr.nextTag();
StaxUtils.toNextElement(dxr);
assertEquals(XMLFault.XML_FAULT_STRING,dxr.getLocalName());
assertEquals(fault.toString(),dxr.getElementText());
dxr.nextTag();
StaxUtils.toNextElement(dxr);
assertEquals(XMLFault.XML_FAULT_DETAIL,dxr.getLocalName());
dxr.nextTag();
StaxUtils.toNextElement(dxr);
assertEquals("faultDetail",dxr.getLocalName());
}
Class: org.apache.cxf.binding.xml.interceptor.XMLMessageOutInterceptorTest BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testBareOutMultiWithRoot() throws Exception {
MyComplexStructType myComplexStruct=new MyComplexStructType();
myComplexStruct.setElem1("elem1");
myComplexStruct.setElem2("elem2");
myComplexStruct.setElem3(45);
params.add("tli");
params.add(myComplexStruct);
common("/wsdl/hello_world_xml_bare.wsdl",new QName(bareNs,"XMLPort"),MyComplexStructType.class);
BindingInfo bi=super.serviceInfo.getBinding(new QName(bareNs,"Greeter_XMLBinding"));
BindingOperationInfo boi=bi.getOperation(new QName(bareNs,"testMultiParamPart"));
xmlMessage.getExchange().put(BindingOperationInfo.class,boi);
out.handleMessage(xmlMessage);
XMLStreamReader reader=getXMLReader();
DepthXMLStreamReader dxr=new DepthXMLStreamReader(reader);
StaxUtils.nextEvent(dxr);
StaxUtils.toNextElement(dxr);
assertEquals(bareNs,dxr.getNamespaceURI());
assertEquals("multiParamRootReq",dxr.getLocalName());
StaxUtils.nextEvent(dxr);
StaxUtils.toNextElement(dxr);
assertEquals(bareRequestTypeQName,dxr.getName());
StaxUtils.nextEvent(dxr);
if (StaxUtils.toNextText(dxr)) {
assertEquals("tli",dxr.getText());
}
boolean foundRequest=false;
while (true) {
StaxUtils.nextEvent(dxr);
StaxUtils.toNextElement(dxr);
QName requestType=new QName(dxr.getNamespaceURI(),dxr.getLocalName());
if (requestType.equals(bareMyComplexStructQName)) {
foundRequest=true;
break;
}
}
assertEquals("found request type",true,foundRequest);
}
InternalCallVerifier EqualityVerifier
@Test public void testBareOutSingle() throws Exception {
MyComplexStructType myComplexStruct=new MyComplexStructType();
myComplexStruct.setElem1("elem1");
myComplexStruct.setElem2("elem2");
myComplexStruct.setElem3(45);
params.add(myComplexStruct);
common("/wsdl/hello_world_xml_bare.wsdl",new QName(bareNs,"XMLPort"),MyComplexStructType.class);
BindingInfo bi=super.serviceInfo.getBinding(new QName(bareNs,"Greeter_XMLBinding"));
BindingOperationInfo boi=bi.getOperation(new QName(bareNs,"sendReceiveData"));
xmlMessage.getExchange().put(BindingOperationInfo.class,boi);
out.handleMessage(xmlMessage);
XMLStreamReader reader=getXMLReader();
DepthXMLStreamReader dxr=new DepthXMLStreamReader(reader);
StaxUtils.nextEvent(dxr);
StaxUtils.toNextElement(dxr);
assertEquals(bareMyComplexStructTypeQName.getLocalPart(),dxr.getLocalName());
StaxUtils.toNextElement(dxr);
StaxUtils.toNextText(dxr);
assertEquals(myComplexStruct.getElem1(),dxr.getText());
}
InternalCallVerifier EqualityVerifier
@Test public void testWrapOut() throws Exception {
GreetMe greetMe=new GreetMe();
greetMe.setRequestType("tli");
params.add(greetMe);
common("/wsdl/hello_world_xml_wrapped.wsdl",new QName(wrapNs,"XMLPort"),GreetMe.class);
BindingInfo bi=super.serviceInfo.getBinding(new QName(wrapNs,"Greeter_XMLBinding"));
BindingOperationInfo boi=bi.getOperation(new QName(wrapNs,"greetMe"));
xmlMessage.getExchange().put(BindingOperationInfo.class,boi);
out.handleMessage(xmlMessage);
XMLStreamReader reader=getXMLReader();
DepthXMLStreamReader dxr=new DepthXMLStreamReader(reader);
StaxUtils.nextEvent(dxr);
StaxUtils.toNextElement(dxr);
assertEquals(wrapGreetMeQName.getNamespaceURI(),dxr.getNamespaceURI());
assertEquals(wrapGreetMeQName.getLocalPart(),dxr.getLocalName());
StaxUtils.toNextElement(dxr);
StaxUtils.toNextText(dxr);
assertEquals(greetMe.getRequestType(),dxr.getText());
}
Class: org.apache.cxf.bus.CXFBusImplTest InternalCallVerifier EqualityVerifier
@Test public void testBusID(){
Bus bus=new ExtensionManagerBus();
String id=bus.getId();
assertEquals("The bus id should be cxf",id,Bus.DEFAULT_BUS_ID + Math.abs(bus.hashCode()));
bus.setId("test");
assertEquals("The bus id should be changed","test",bus.getId());
bus.shutdown(true);
}
InternalCallVerifier NullVerifier
@Test public void testConstructionWithoutExtensions() throws BusException {
Bus bus=new ExtensionManagerBus();
assertNotNull(bus.getExtension(BindingFactoryManager.class));
assertNotNull(bus.getExtension(ConduitInitiatorManager.class));
assertNotNull(bus.getExtension(DestinationFactoryManager.class));
assertNotNull(bus.getExtension(PhaseManager.class));
bus.shutdown(true);
}
InternalCallVerifier IdentityVerifier
@Test public void testConstructionWithExtensions() throws BusException {
IMocksControl control;
BindingFactoryManager bindingFactoryManager;
InstrumentationManager instrumentationManager;
PhaseManager phaseManager;
control=EasyMock.createNiceControl();
Map,Object> extensions=new HashMap,Object>();
bindingFactoryManager=control.createMock(BindingFactoryManager.class);
instrumentationManager=control.createMock(InstrumentationManager.class);
phaseManager=control.createMock(PhaseManager.class);
extensions.put(BindingFactoryManager.class,bindingFactoryManager);
extensions.put(InstrumentationManager.class,instrumentationManager);
extensions.put(PhaseManager.class,phaseManager);
Bus bus=new ExtensionManagerBus(extensions);
assertSame(bindingFactoryManager,bus.getExtension(BindingFactoryManager.class));
assertSame(instrumentationManager,bus.getExtension(InstrumentationManager.class));
assertSame(phaseManager,bus.getExtension(PhaseManager.class));
}
InternalCallVerifier IdentityVerifier
@Test public void testExtensions(){
Bus bus=new ExtensionManagerBus();
String extension="CXF";
bus.setExtension(extension,String.class);
assertSame(extension,bus.getExtension(String.class));
bus.shutdown(true);
}
Class: org.apache.cxf.bus.extension.ExtensionTest BooleanVerifier InternalCallVerifier
@Test public void testLoad() throws ExtensionException {
Extension e=new Extension();
ClassLoader cl=Thread.currentThread().getContextClassLoader();
e.setClassname("no.such.Extension");
try {
e.load(cl,null);
}
catch ( ExtensionException ex) {
assertTrue("ExtensionException does not wrap ClassNotFoundException",ex.getCause() instanceof ClassNotFoundException);
}
e.setClassname("java.lang.System");
try {
e.load(cl,null);
}
catch ( ExtensionException ex) {
assertTrue("ExtensionException does not wrap NoSuchMethodException " + ex.getCause(),ex.getCause() instanceof NoSuchMethodException);
}
e.setClassname(MyServiceConstructorThrowsException.class.getName());
try {
e.load(cl,null);
}
catch ( ExtensionException ex) {
assertTrue("ExtensionException does not wrap IllegalArgumentException",ex.getCause() instanceof IllegalArgumentException);
}
e.setClassname("java.lang.String");
Object obj=e.load(cl,null);
assertTrue("Object is not type String",obj instanceof String);
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testLoadInterface(){
Extension e=new Extension();
ClassLoader cl=Thread.currentThread().getContextClassLoader();
e.setInterfaceName("no.such.Extension");
try {
e.loadInterface(cl);
}
catch ( ExtensionException ex) {
assertTrue("ExtensionException does not wrap ClassNotFoundException",ex.getCause() instanceof ClassNotFoundException);
}
e.setInterfaceName(Assert.class.getName());
Class> cls=e.loadInterface(cl);
assertNotNull(cls);
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testMutators(){
Extension e=new Extension();
String className="org.apache.cxf.bindings.soap.SoapBinding";
e.setClassname(className);
assertEquals("Unexpected class name.",className,e.getClassname());
assertNull("Unexpected interface name.",e.getInterfaceName());
String interfaceName="org.apache.cxf.bindings.Binding";
e.setInterfaceName(interfaceName);
assertEquals("Unexpected interface name.",interfaceName,e.getInterfaceName());
assertTrue("Extension is deferred.",!e.isDeferred());
e.setDeferred(true);
assertTrue("Extension is not deferred.",e.isDeferred());
assertEquals("Unexpected size of namespace list.",0,e.getNamespaces().size());
}
Class: org.apache.cxf.bus.extension.TextExtensionFragmentParserTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetExtensions() throws IOException {
InputStream is=TextExtensionFragmentParserTest.class.getResourceAsStream("extension2.txt");
List extensions=new TextExtensionFragmentParser(null).getExtensions(is);
assertEquals("Unexpected number of Extension elements.",3,extensions.size());
Extension e=extensions.get(0);
assertTrue("Extension is deferred.",!e.isDeferred());
assertEquals("Unexpected class name.","org.apache.cxf.foo.FooImpl",e.getClassname());
assertEquals("Unexpected number of namespace elements.",0,e.getNamespaces().size());
e=extensions.get(1);
assertTrue("Extension is not deferred.",e.isDeferred());
assertEquals("Unexpected implementation class name.","java.lang.Boolean",e.getClassname());
assertNull("Interface should be null",e.getInterfaceName());
assertEquals("Unexpected number of namespace elements.",0,e.getNamespaces().size());
}
Class: org.apache.cxf.bus.managers.EndpointResolverRegistryImplTest InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testMintFromServiceName(){
registry.register(resolver1);
registry.register(resolver2);
resolver1.mint(serviceName);
EasyMock.expectLastCall().andReturn(logical);
control.replay();
EndpointReferenceType minted=registry.mint(serviceName);
control.verify();
assertSame("unexpected minted EPR",logical,minted);
control.reset();
resolver1.mint(serviceName);
EasyMock.expectLastCall().andReturn(null);
resolver2.mint(serviceName);
EasyMock.expectLastCall().andReturn(logical);
control.replay();
minted=registry.mint(serviceName);
control.verify();
assertSame("unexpected minted EPR",logical,minted);
control.reset();
resolver1.mint(serviceName);
EasyMock.expectLastCall().andReturn(null);
resolver2.mint(serviceName);
EasyMock.expectLastCall().andReturn(null);
control.replay();
minted=registry.mint(serviceName);
control.verify();
assertNull("unexpected minted EPR",minted);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testRegister(){
assertEquals("unexpected resolver count",0,registry.getResolvers().size());
registry.register(resolver1);
assertEquals("unexpected resolver count",1,registry.getResolvers().size());
assertTrue("expected resolver to be registered",registry.getResolvers().contains(resolver1));
registry.unregister(resolver1);
assertEquals("unexpected resolver count",0,registry.getResolvers().size());
assertFalse("expected resolver to be registered",registry.getResolvers().contains(resolver1));
registry.register(resolver2);
registry.register(resolver1);
assertEquals("unexpected resolver count",2,registry.getResolvers().size());
assertTrue("expected resolver to be registered",registry.getResolvers().contains(resolver1));
assertTrue("expected resolver to be registered",registry.getResolvers().contains(resolver2));
registry.unregister(resolver2);
assertEquals("unexpected resolver count",1,registry.getResolvers().size());
assertTrue("expected resolver to be registered",registry.getResolvers().contains(resolver1));
assertFalse("expected resolver to be registered",registry.getResolvers().contains(resolver2));
}
InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testMintFromPhysical(){
registry.register(resolver1);
registry.register(resolver2);
resolver1.mint(physical);
EasyMock.expectLastCall().andReturn(logical);
control.replay();
EndpointReferenceType minted=registry.mint(physical);
control.verify();
assertSame("unexpected minted EPR",logical,minted);
control.reset();
resolver1.mint(physical);
EasyMock.expectLastCall().andReturn(null);
resolver2.mint(physical);
EasyMock.expectLastCall().andReturn(logical);
control.replay();
minted=registry.mint(physical);
control.verify();
assertSame("unexpected minted EPR",logical,minted);
control.reset();
resolver1.mint(physical);
EasyMock.expectLastCall().andReturn(null);
resolver2.mint(physical);
EasyMock.expectLastCall().andReturn(null);
control.replay();
minted=registry.mint(physical);
control.verify();
assertNull("unexpected minted EPR",minted);
}
InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testRenew(){
registry.register(resolver1);
registry.register(resolver2);
resolver1.renew(logical,physical);
EasyMock.expectLastCall().andReturn(fresh);
control.replay();
EndpointReferenceType renewed=registry.renew(logical,physical);
control.verify();
assertSame("unexpected physical EPR",fresh,renewed);
control.reset();
resolver1.renew(logical,physical);
EasyMock.expectLastCall().andReturn(null);
resolver2.renew(logical,physical);
EasyMock.expectLastCall().andReturn(physical);
control.replay();
renewed=registry.renew(logical,physical);
control.verify();
assertSame("unexpected physical EPR",physical,renewed);
control.reset();
resolver1.renew(logical,physical);
EasyMock.expectLastCall().andReturn(null);
resolver2.renew(logical,physical);
EasyMock.expectLastCall().andReturn(null);
control.replay();
renewed=registry.renew(logical,physical);
control.verify();
assertNull("unexpected physical EPR",renewed);
}
InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testResolve(){
registry.register(resolver1);
registry.register(resolver2);
resolver1.resolve(logical);
EasyMock.expectLastCall().andReturn(physical);
control.replay();
EndpointReferenceType resolved=registry.resolve(logical);
control.verify();
assertSame("unexpected physical EPR",physical,resolved);
control.reset();
resolver1.resolve(logical);
EasyMock.expectLastCall().andReturn(null);
resolver2.resolve(logical);
EasyMock.expectLastCall().andReturn(physical);
control.replay();
resolved=registry.resolve(logical);
control.verify();
assertSame("unexpected physical EPR",physical,resolved);
control.reset();
resolver1.resolve(logical);
EasyMock.expectLastCall().andReturn(null);
resolver2.resolve(logical);
EasyMock.expectLastCall().andReturn(null);
control.replay();
resolved=registry.resolve(logical);
control.verify();
assertNull("unexpected physical EPR",resolved);
}
Class: org.apache.cxf.bus.managers.ServerRegistryImpTest InternalCallVerifier EqualityVerifier
@Test public void testServerRegistryPreShutdown(){
ServerRegistryImpl serverRegistryImpl=new ServerRegistryImpl();
Server server=new DummyServer(serverRegistryImpl);
server.start();
assertEquals("The serverList should have one service",serverRegistryImpl.serversList.size(),1);
serverRegistryImpl.preShutdown();
assertEquals("The serverList should be clear ",serverRegistryImpl.serversList.size(),0);
serverRegistryImpl.postShutdown();
assertEquals("The serverList should be clear ",serverRegistryImpl.serversList.size(),0);
}
Class: org.apache.cxf.bus.managers.ServiceContractResolverRegistryImplTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testRegister(){
assertEquals("unexpected resolver count",0,registry.getResolvers().size());
registry.register(resolver1);
assertEquals("unexpected resolver count",1,registry.getResolvers().size());
assertTrue("expected resolver to be registered",registry.getResolvers().contains(resolver1));
registry.unregister(resolver1);
assertEquals("unexpected resolver count",0,registry.getResolvers().size());
assertFalse("expected resolver to be registered",registry.getResolvers().contains(resolver1));
registry.register(resolver2);
registry.register(resolver1);
assertEquals("unexpected resolver count",2,registry.getResolvers().size());
assertTrue("expected resolver to be registered",registry.getResolvers().contains(resolver1));
assertTrue("expected resolver to be registered",registry.getResolvers().contains(resolver2));
registry.unregister(resolver2);
assertEquals("unexpected resolver count",1,registry.getResolvers().size());
assertTrue("expected resolver to be registered",registry.getResolvers().contains(resolver1));
assertFalse("expected resolver to be registered",registry.getResolvers().contains(resolver2));
}
InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testGetContactLocation(){
registry.register(resolver1);
registry.register(resolver2);
resolver1.getContractLocation(serviceName);
EasyMock.expectLastCall().andReturn(uri1);
control.replay();
URI resolved=registry.getContractLocation(serviceName);
control.verify();
assertSame("unexpected physical EPR",uri1,resolved);
control.reset();
resolver1.getContractLocation(serviceName);
EasyMock.expectLastCall().andReturn(null);
resolver2.getContractLocation(serviceName);
EasyMock.expectLastCall().andReturn(uri2);
control.replay();
resolved=registry.getContractLocation(serviceName);
control.verify();
assertSame("unexpected physical EPR",uri2,resolved);
assertNotSame("unexpected physical EPR",uri1,resolved);
control.reset();
resolver1.getContractLocation(serviceName);
EasyMock.expectLastCall().andReturn(null);
resolver2.getContractLocation(serviceName);
EasyMock.expectLastCall().andReturn(null);
control.replay();
resolved=registry.getContractLocation(serviceName);
control.verify();
assertNull("unexpected physical EPR",resolved);
}
Class: org.apache.cxf.bus.spring.BusDefinitionParserTest BooleanVerifier InternalCallVerifier
@Test public void testBusConfigure(){
ClassPathXmlApplicationContext context=null;
try {
context=new ClassPathXmlApplicationContext("org/apache/cxf/bus/spring/customerBus.xml");
Bus cxf1=(Bus)context.getBean("cxf1");
assertTrue(cxf1.getOutInterceptors().size() == 1);
assertTrue(cxf1.getInInterceptors().size() == 0);
Bus cxf2=(Bus)context.getBean("cxf2");
assertTrue(cxf2.getInInterceptors().size() == 1);
assertTrue(cxf2.getOutInterceptors().size() == 0);
}
finally {
if (context != null) {
context.close();
}
}
}
BooleanVerifier InternalCallVerifier
@Test public void testBusConfigureCreateBus(){
ClassPathXmlApplicationContext context=null;
final AtomicBoolean b=new AtomicBoolean();
try {
context=new ClassPathXmlApplicationContext("org/apache/cxf/bus/spring/customerBus2.xml");
Bus cxf1=(Bus)context.getBean("cxf1");
assertTrue(cxf1.getOutInterceptors().size() == 1);
assertTrue(cxf1.getInInterceptors().size() == 0);
Bus cxf2=(Bus)context.getBean("cxf2");
assertTrue(cxf2.getInInterceptors().size() == 1);
assertTrue(cxf2.getOutInterceptors().size() == 0);
cxf2.getExtension(BusLifeCycleManager.class).registerLifeCycleListener(new BusLifeCycleListener(){
public void initComplete(){
}
public void preShutdown(){
}
public void postShutdown(){
b.set(true);
}
}
);
}
finally {
if (context != null) {
context.close();
}
}
assertTrue("postShutdown not called",b.get());
}
Class: org.apache.cxf.bus.spring.SpringBusFactoryTest InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testInitialisation(){
Bus bus=new SpringBusFactory().createBus("org/apache/cxf/bus/spring/init.xml");
assertNotNull(bus.getExtension(TestListener.class));
assertSame(bus,bus.getExtension(BusApplicationContext.class).getBean("cxf"));
}
BooleanVerifier InternalCallVerifier
@Test public void testJsr250(){
Bus bus=new SpringBusFactory().createBus("org/apache/cxf/bus/spring/testjsr250.xml");
TestExtension te=bus.getExtension(TestExtension.class);
assertTrue("@PostConstruct annotated method has not been called.",te.postConstructMethodCalled);
assertTrue("@PreDestroy annoated method has been called already.",!te.preDestroyMethodCalled);
bus.shutdown(true);
assertTrue("@PreDestroy annotated method has not been called.",te.preDestroyMethodCalled);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testDefault(){
Bus bus=new SpringBusFactory().createBus();
assertNotNull(bus);
BindingFactoryManager bfm=bus.getExtension(BindingFactoryManager.class);
assertNotNull("No binding factory manager",bfm);
assertNotNull("No configurer",bus.getExtension(Configurer.class));
assertNotNull("No resource manager",bus.getExtension(ResourceManager.class));
assertNotNull("No destination factory manager",bus.getExtension(DestinationFactoryManager.class));
assertNotNull("No conduit initiator manager",bus.getExtension(ConduitInitiatorManager.class));
assertNotNull("No phase manager",bus.getExtension(PhaseManager.class));
assertNotNull("No workqueue manager",bus.getExtension(WorkQueueManager.class));
assertNotNull("No lifecycle manager",bus.getExtension(BusLifeCycleManager.class));
assertNotNull("No service registry",bus.getExtension(ServerRegistry.class));
try {
bfm.getBindingFactory("http://cxf.apache.org/unknown");
}
catch ( BusException ex) {
}
assertEquals("Unexpected interceptors",0,bus.getInInterceptors().size());
assertEquals("Unexpected interceptors",0,bus.getInFaultInterceptors().size());
assertEquals("Unexpected interceptors",0,bus.getOutInterceptors().size());
assertEquals("Unexpected interceptors",0,bus.getOutFaultInterceptors().size());
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testPhases(){
Bus bus=new SpringBusFactory().createBus();
PhaseManager cxfPM=bus.getExtension(PhaseManager.class);
PhaseManager defaultPM=new PhaseManagerImpl();
SortedSet cxfPhases=cxfPM.getInPhases();
SortedSet defaultPhases=defaultPM.getInPhases();
assertEquals(defaultPhases.size(),cxfPhases.size());
assertTrue(cxfPhases.equals(defaultPhases));
cxfPhases=cxfPM.getOutPhases();
defaultPhases=defaultPM.getOutPhases();
assertEquals(defaultPhases.size(),cxfPhases.size());
assertTrue(cxfPhases.equals(defaultPhases));
}
Class: org.apache.cxf.configuration.spring.ConfigurerImplTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testAddApplicationContext(){
ConfigurableApplicationContext context1=new ClassPathXmlApplicationContext("/org/apache/cxf/configuration/spring/test-beans.xml");
ConfigurerImpl configurer=new ConfigurerImpl();
configurer.setApplicationContext(context1);
context1.close();
ConfigurableApplicationContext context2=new ClassPathXmlApplicationContext("/org/apache/cxf/configuration/spring/test-beans.xml");
configurer.addApplicationContext(context2);
Set contexts=configurer.getAppContexts();
assertEquals("The Context's size is wrong",1,contexts.size());
assertTrue("The conetxts' contains a wrong application context",contexts.contains(context2));
}
APIUtilityVerifier IterativeVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testConfigureSimpleNoMatchingBean(){
SimpleBean sb=new SimpleBean("unknown");
BusApplicationContext ac=new BusApplicationContext("/org/apache/cxf/configuration/spring/test-beans.xml",false);
ConfigurerImpl configurer=new ConfigurerImpl(ac);
configurer.configureBean(sb);
assertEquals("Unexpected value for attribute stringAttr","hello",sb.getStringAttr());
assertTrue("Unexpected value for attribute booleanAttr",sb.getBooleanAttr());
assertEquals("Unexpected value for attribute integerAttr",BigInteger.ONE,sb.getIntegerAttr());
assertEquals("Unexpected value for attribute intAttr",Integer.valueOf(2),sb.getIntAttr());
assertEquals("Unexpected value for attribute longAttr",Long.valueOf(3L),sb.getLongAttr());
assertEquals("Unexpected value for attribute shortAttr",Short.valueOf((short)4),sb.getShortAttr());
assertEquals("Unexpected value for attribute decimalAttr",new BigDecimal("5"),sb.getDecimalAttr());
assertEquals("Unexpected value for attribute floatAttr",new Float(6F),sb.getFloatAttr());
assertEquals("Unexpected value for attribute doubleAttr",Double.valueOf(7.0D),sb.getDoubleAttr());
assertEquals("Unexpected value for attribute byteAttr",Byte.valueOf((byte)8),sb.getByteAttr());
QName qn=sb.getQnameAttr();
assertEquals("Unexpected value for attribute qnameAttrNoDefault","schema",qn.getLocalPart());
assertEquals("Unexpected value for attribute qnameAttrNoDefault","http://www.w3.org/2001/XMLSchema",qn.getNamespaceURI());
byte[] expected=DatatypeConverter.parseBase64Binary("abcd");
byte[] val=sb.getBase64BinaryAttr();
assertEquals("Unexpected value for attribute base64BinaryAttrNoDefault",expected.length,val.length);
for (int i=0; i < expected.length; i++) {
assertEquals("Unexpected value for attribute base64BinaryAttrNoDefault",expected[i],val[i]);
}
expected=new HexBinaryAdapter().unmarshal("aaaa");
val=sb.getHexBinaryAttr();
assertEquals("Unexpected value for attribute hexBinaryAttrNoDefault",expected.length,val.length);
for (int i=0; i < expected.length; i++) {
assertEquals("Unexpected value for attribute hexBinaryAttrNoDefault",expected[i],val[i]);
}
assertEquals("Unexpected value for attribute unsignedIntAttrNoDefault",Long.valueOf(9L),sb.getUnsignedIntAttr());
assertEquals("Unexpected value for attribute unsignedShortAttrNoDefault",Integer.valueOf(10),sb.getUnsignedShortAttr());
assertEquals("Unexpected value for attribute unsignedByteAttrNoDefault",Short.valueOf((short)11),sb.getUnsignedByteAttr());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetBeanName(){
ConfigurerImpl configurer=new ConfigurerImpl();
Object beanInstance=new Configurable(){
public String getBeanName(){
return "a";
}
}
;
assertEquals("a",configurer.getBeanName(beanInstance));
final class NamedBean {
@SuppressWarnings("unused") public String getBeanName(){
return "b";
}
}
beanInstance=new NamedBean();
assertEquals("b",configurer.getBeanName(beanInstance));
beanInstance=this;
assertNull(configurer.getBeanName(beanInstance));
}
Class: org.apache.cxf.continuations.SuspendedInvocationExceptionTest InternalCallVerifier IdentityVerifier
@Test public void testValidRuntimeException(){
Throwable t=new UncheckedException(new Throwable());
SuspendedInvocationException ex=new SuspendedInvocationException(t);
assertSame(t,ex.getRuntimeException());
assertSame(t,ex.getCause());
}
Class: org.apache.cxf.cxf1226.MissingQualification1226Test APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void lookForMissingNamespace() throws Exception {
EndpointImpl endpoint=getBean(EndpointImpl.class,"helloWorld");
Document d=getWSDLDocument(endpoint.getServer());
NodeList schemas=assertValid("//xsd:schema[@targetNamespace='http://nstest.helloworld']",d);
Element schemaElement=(Element)schemas.item(0);
String ef=schemaElement.getAttribute("elementFormDefault");
assertEquals("qualified",ef);
}
Class: org.apache.cxf.cxf2006.RespectBindingFeatureClientServerTest InternalCallVerifier EqualityVerifier
@Test public void testRespectBindingFeatureFalse() throws Exception {
startServers("/wsdl_systest/cxf2006.wsdl");
GreeterRPCLit greeter=service.getPort(portName,GreeterRPCLit.class,new RespectBindingFeature(false));
updateAddressPort(greeter,PORT);
assertEquals("Bonjour",greeter.sayHi());
}
Class: org.apache.cxf.databinding.source.XMLStreamDataReaderTest APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testCloseOriginalInputStream() throws Exception {
XMLStreamDataReader reader=new XMLStreamDataReader();
Message msg=new MessageImpl();
TestInputStream in1=new TestInputStream(DUMMY_DATA);
msg.setContent(InputStream.class,in1);
reader.setProperty(Message.class.getName(),msg);
Object obj=reader.read(new QName("http://www.apache.org/cxf","dummy"),StaxUtils.createXMLStreamReader(in1),XMLStreamReader.class);
assertTrue(obj instanceof XMLStreamReader);
assertFalse(in1.isClosed());
((XMLStreamReader)obj).close();
assertTrue(in1.isClosed());
}
Class: org.apache.cxf.doclitbare.DocLitBareTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testNamespaceCrash(){
ServerFactoryBean svrFactory=new ServerFactoryBean();
svrFactory.setServiceClass(University.class);
svrFactory.setTransportId(LocalTransportFactory.TRANSPORT_ID);
svrFactory.setAddress("local://dlbTest");
svrFactory.setServiceBean(new UniversityImpl());
svrFactory.getServiceFactory().setDataBinding(new AegisDatabinding());
svrFactory.create();
ClientProxyFactoryBean factory=new ClientProxyFactoryBean();
factory.getServiceFactory().setDataBinding(new AegisDatabinding());
factory.setServiceClass(University.class);
factory.setTransportId(LocalTransportFactory.TRANSPORT_ID);
factory.setAddress("local://dlbTest");
University client=(University)factory.create();
Teacher tr=client.getTeacher(new Course(40,"Intro to CS","Introductory Comp Sci"));
assertNotNull(tr);
assertEquals(52,tr.getAge());
assertEquals("Mr. Tom",tr.getName());
}
Class: org.apache.cxf.endpoint.EndpointImplTest BooleanVerifier InternalCallVerifier
@Test public void testEqualsAndHashCode() throws Exception {
Bus bus=new ExtensionManagerBus();
Service svc=new ServiceImpl();
EndpointInfo ei=new EndpointInfo();
ei.setAddress("http://nowhere.com/bar/foo");
EndpointInfo ei2=new EndpointInfo();
ei2.setAddress("http://nowhere.com/foo/bar");
Endpoint ep=new EndpointImpl(bus,svc,ei);
Endpoint ep1=new EndpointImpl(bus,svc,ei);
Endpoint ep2=new EndpointImpl(bus,svc,ei2);
int hashcode=ep.hashCode();
int hashcode1=ep1.hashCode();
int hashcode2=ep2.hashCode();
assertTrue("hashcodes must be equal",hashcode == hashcode1);
assertTrue("hashcodes must not be equal",hashcode != hashcode2);
assertTrue("reflexivity violated",ep.equals(ep));
assertFalse("two objects must not be equal",ep.equals(ep1));
assertFalse("two objects must not be equal",ep.equals(ep2));
ep.put("custom",Boolean.TRUE);
assertTrue("hashcode must remain equal",hashcode == ep.hashCode());
}
Class: org.apache.cxf.ext.logging.DefaultLogEventMapperTest InternalCallVerifier EqualityVerifier
/**
* Test for NPE described in CXF-6436
*/
@Test public void testNullValues(){
DefaultLogEventMapper mapper=new DefaultLogEventMapper();
Message message=new MessageImpl();
message.put(Message.HTTP_REQUEST_METHOD,null);
message.put(Message.REQUEST_URI,null);
Exchange exchange=new ExchangeImpl();
message.setExchange(exchange);
LogEvent event=mapper.map(message);
Assert.assertEquals("",event.getOperationName());
}
InternalCallVerifier EqualityVerifier
@Test public void testRest(){
DefaultLogEventMapper mapper=new DefaultLogEventMapper();
Message message=new MessageImpl();
message.put(Message.HTTP_REQUEST_METHOD,"GET");
message.put(Message.REQUEST_URI,"test");
Exchange exchange=new ExchangeImpl();
message.setExchange(exchange);
LogEvent event=mapper.map(message);
Assert.assertEquals("GET[test]",event.getOperationName());
}
InternalCallVerifier EqualityVerifier
@Test public void testSoap(){
DefaultLogEventMapper mapper=new DefaultLogEventMapper();
Message message=new MessageImpl();
ExchangeImpl exchange=new ExchangeImpl();
ServiceInfo service=new ServiceInfo();
BindingInfo info=new BindingInfo(service,"bindingId");
SoapBinding value=new SoapBinding(info);
exchange.put(Binding.class,value);
OperationInfo opInfo=new OperationInfo();
opInfo.setName(new QName("http://my","Operation"));
BindingOperationInfo boi=new BindingOperationInfo(info,opInfo);
exchange.put(BindingOperationInfo.class,boi);
message.setExchange(exchange);
LogEvent event=mapper.map(message);
Assert.assertEquals("{http://my}Operation",event.getOperationName());
}
Class: org.apache.cxf.ext.logging.RESTLoggingTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testEvents() throws MalformedURLException {
LoggingFeature loggingFeature=new LoggingFeature();
TestEventSender sender=new TestEventSender();
loggingFeature.setSender(sender);
Server server=createService(loggingFeature);
server.start();
WebClient client=createClient(loggingFeature);
String result=client.get(String.class);
Assert.assertEquals("test1",result);
server.destroy();
List events=sender.getEvents();
Assert.assertEquals(4,events.size());
checkRequestOut(events.get(0));
checkRequestIn(events.get(1));
checkResponseOut(events.get(2));
checkResponseIn(events.get(3));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testSlf4j() throws IOException {
LoggingFeature loggingFeature=new LoggingFeature();
Server server=createService(loggingFeature);
server.start();
WebClient client=createClient(loggingFeature);
String result=client.get(String.class);
Assert.assertEquals("test1",result);
server.destroy();
}
Class: org.apache.cxf.ext.logging.SOAPLoggingTest InternalCallVerifier EqualityVerifier
@Test public void testEvents() throws MalformedURLException {
TestService serviceImpl=new TestServiceImplementation();
LoggingFeature loggingFeature=new LoggingFeature();
TestEventSender sender=new TestEventSender();
loggingFeature.setSender(sender);
Endpoint ep=Endpoint.publish(SERVICE_URI,serviceImpl,loggingFeature);
TestService client=createTestClient(loggingFeature);
client.echo("test");
ep.stop();
List events=sender.getEvents();
Assert.assertEquals(4,events.size());
checkRequestOut(events.get(0));
checkRequestIn(events.get(1));
checkResponseOut(events.get(2));
checkResponseIn(events.get(3));
}
Class: org.apache.cxf.feature.transform.XSLTInterceptorsTest APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void inXMLStreamTest() throws XMLStreamException {
XMLStreamReader xReader=StaxUtils.createXMLStreamReader(messageIS);
message.setContent(XMLStreamReader.class,xReader);
inInterceptor.handleMessage(message);
XMLStreamReader transformedXReader=message.getContent(XMLStreamReader.class);
Document doc=StaxUtils.read(transformedXReader);
Assert.assertTrue("Message was not transformed",checkTransformedXML(doc));
}
BooleanVerifier InternalCallVerifier
@Test public void outStreamTest() throws Exception {
CachedOutputStream cos=new CachedOutputStream();
cos.holdTempFile();
message.setContent(OutputStream.class,cos);
outInterceptor.handleMessage(message);
OutputStream os=message.getContent(OutputStream.class);
IOUtils.copy(messageIS,os);
os.close();
cos.releaseTempFileHold();
Document doc=StaxUtils.read(cos.getInputStream());
Assert.assertTrue("Message was not transformed",checkTransformedXML(doc));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void inReaderTest() throws Exception {
Reader reader=new InputStreamReader(messageIS);
message.setContent(Reader.class,reader);
inInterceptor.handleMessage(message);
Reader transformedReader=message.getContent(Reader.class);
Document doc=StaxUtils.read(transformedReader);
Assert.assertTrue("Message was not transformed",checkTransformedXML(doc));
}
BooleanVerifier InternalCallVerifier
@Test public void outXMLStreamTest() throws XMLStreamException, SAXException, IOException, ParserConfigurationException {
CachedWriter cWriter=new CachedWriter();
cWriter.holdTempFile();
XMLStreamWriter xWriter=StaxUtils.createXMLStreamWriter(cWriter);
message.setContent(XMLStreamWriter.class,xWriter);
outInterceptor.handleMessage(message);
XMLStreamWriter tXWriter=message.getContent(XMLStreamWriter.class);
StaxUtils.copy(new StreamSource(messageIS),tXWriter);
tXWriter.close();
cWriter.releaseTempFileHold();
Document doc=StaxUtils.read(cWriter.getReader());
Assert.assertTrue("Message was not transformed",checkTransformedXML(doc));
}
BooleanVerifier InternalCallVerifier
@Test public void outWriterStreamTest() throws Exception {
CachedWriter cWriter=new CachedWriter();
message.setContent(Writer.class,cWriter);
outInterceptor.handleMessage(message);
Writer tWriter=message.getContent(Writer.class);
IOUtils.copy(new InputStreamReader(messageIS),tWriter,IOUtils.DEFAULT_BUFFER_SIZE);
tWriter.close();
Document doc=StaxUtils.read(cWriter.getReader());
Assert.assertTrue("Message was not transformed",checkTransformedXML(doc));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void inStreamTest() throws Exception {
message.setContent(InputStream.class,messageIS);
inInterceptor.handleMessage(message);
InputStream transformedIS=message.getContent(InputStream.class);
Document doc=StaxUtils.read(transformedIS);
Assert.assertTrue("Message was not transformed",checkTransformedXML(doc));
}
Class: org.apache.cxf.frontend.soap.SoapBindingSelectionTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testMultipleSoapBindings() throws Exception {
ServerFactoryBean svrBean1=new ServerFactoryBean();
svrBean1.setAddress("http://localhost/Hello");
svrBean1.setServiceClass(HelloService.class);
svrBean1.setServiceBean(new HelloServiceImpl());
svrBean1.setBus(getBus());
svrBean1.getInInterceptors().add(new AbstractPhaseInterceptor(Phase.USER_LOGICAL){
public void handleMessage( Message message) throws Fault {
service1Invoked=true;
}
}
);
svrBean1.create();
ServerFactoryBean svrBean2=new ServerFactoryBean();
svrBean2.setAddress("http://localhost/Hello");
svrBean2.setServiceClass(HelloService.class);
svrBean2.setServiceBean(new HelloServiceImpl());
svrBean2.setBus(getBus());
svrBean2.getInInterceptors().add(new AbstractPhaseInterceptor(Phase.USER_LOGICAL){
public void handleMessage( Message message) throws Fault {
service2Invoked=true;
}
}
);
SoapBindingConfiguration config=new SoapBindingConfiguration();
config.setVersion(Soap12.getInstance());
svrBean2.setBindingConfig(config);
ServerImpl server2=(ServerImpl)svrBean2.create();
Destination d=server2.getDestination();
MessageObserver mo=d.getMessageObserver();
assertTrue(mo instanceof MultipleEndpointObserver);
MultipleEndpointObserver meo=(MultipleEndpointObserver)mo;
assertEquals(2,meo.getEndpoints().size());
Node nd=invoke("http://localhost/Hello",LocalTransportFactory.TRANSPORT_ID,"soap11.xml");
assertEquals("http://schemas.xmlsoap.org/soap/envelope/",getNs(nd));
assertTrue(service1Invoked);
assertFalse(service2Invoked);
service1Invoked=false;
nd=invoke("http://localhost/Hello",LocalTransportFactory.TRANSPORT_ID,"soap12.xml");
assertEquals("http://www.w3.org/2003/05/soap-envelope",getNs(nd));
assertFalse(service1Invoked);
assertTrue(service2Invoked);
server2.stop();
server2.start();
nd=invoke("http://localhost/Hello",LocalTransportFactory.TRANSPORT_ID,"soap12.xml");
assertEquals("http://www.w3.org/2003/05/soap-envelope",getNs(nd));
assertFalse(service1Invoked);
assertTrue(service2Invoked);
}
Class: org.apache.cxf.frontend.spring.ClientServerTest BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testClientServer(){
ctx=new ClassPathXmlApplicationContext(new String[]{"/org/apache/cxf/frontend/spring/rountrip.xml"});
HelloService greeter=(HelloService)ctx.getBean("client");
assertNotNull(greeter);
String result=greeter.sayHello();
assertEquals("We get the wrong sayHello result","hello",result);
Client c=ClientProxy.getClient(greeter);
TestInterceptor out=new TestInterceptor();
TestInterceptor in=new TestInterceptor();
c.getRequestContext().put(Message.OUT_INTERCEPTORS,Arrays.asList(new Interceptor[]{out}));
result=greeter.sayHello();
assertTrue(out.wasCalled());
out.reset();
c.getRequestContext().put(Message.IN_INTERCEPTORS,Arrays.asList(new Interceptor[]{in}));
result=greeter.sayHello();
assertTrue(out.wasCalled());
assertTrue(in.wasCalled());
ctx.close();
BusFactory.setDefaultBus(null);
}
Class: org.apache.cxf.frontend.spring.SpringBeansTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testClients() throws Exception {
AbstractFactoryBeanDefinitionParser.setFactoriesAreAbstract(false);
ctx=new ClassPathXmlApplicationContext(new String[]{"/org/apache/cxf/frontend/spring/clients.xml"});
Object bean=ctx.getBean("client1.proxyFactory");
assertNotNull(bean);
ClientProxyFactoryBean cpfbean=(ClientProxyFactoryBean)bean;
BindingConfiguration bc=cpfbean.getBindingConfig();
assertTrue(bc instanceof SoapBindingConfiguration);
SoapBindingConfiguration sbc=(SoapBindingConfiguration)bc;
assertTrue(sbc.getVersion() instanceof Soap12);
HelloService greeter=(HelloService)ctx.getBean("client1");
assertNotNull(greeter);
Client client=ClientProxy.getClient(greeter);
assertNotNull("expected ConduitSelector",client.getConduitSelector());
assertTrue("unexpected ConduitSelector",client.getConduitSelector() instanceof NullConduitSelector);
List> inInterceptors=client.getInInterceptors();
boolean saaj=false;
boolean logging=false;
for ( Interceptor extends Message> i : inInterceptors) {
if (i instanceof SAAJInInterceptor) {
saaj=true;
}
else if (i instanceof LoggingInInterceptor) {
logging=true;
}
}
assertTrue(saaj);
assertTrue(logging);
saaj=false;
logging=false;
for ( Interceptor> i : client.getOutInterceptors()) {
if (i instanceof SAAJOutInterceptor) {
saaj=true;
}
else if (i instanceof LoggingOutInterceptor) {
logging=true;
}
}
assertTrue(saaj);
assertTrue(logging);
ClientProxyFactoryBean clientProxyFactoryBean=(ClientProxyFactoryBean)ctx.getBean("client2.proxyFactory");
assertNotNull(clientProxyFactoryBean);
assertEquals("get the wrong transportId",clientProxyFactoryBean.getTransportId(),"http://cxf.apache.org/transports/local");
assertEquals("get the wrong bindingId",clientProxyFactoryBean.getBindingId(),"http://cxf.apache.org/bindings/xformat");
greeter=(HelloService)ctx.getBean("client2");
assertNotNull(greeter);
greeter=(HelloService)ctx.getBean("client3");
assertNotNull(greeter);
client=ClientProxy.getClient(greeter);
EndpointInfo epi=client.getEndpoint().getEndpointInfo();
AuthorizationPolicy ap=epi.getExtensor(AuthorizationPolicy.class);
assertNotNull("The AuthorizationPolicy instance should not be null",ap);
assertEquals("Get the wrong username",ap.getUserName(),"testUser");
assertEquals("Get the wrong password",ap.getPassword(),"password");
}
BranchVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testServers() throws Exception {
ctx=new ClassPathXmlApplicationContext(new String[]{"/org/apache/cxf/frontend/spring/servers.xml"});
ServerFactoryBean bean=(ServerFactoryBean)ctx.getBean("simple");
assertNotNull(bean);
if (!(bean.getServiceBean() instanceof HelloServiceImpl)) {
fail("can't get the right serviceBean");
}
bean=(ServerFactoryBean)ctx.getBean("inlineImplementor");
if (!(bean.getServiceBean() instanceof HelloServiceImpl)) {
fail("can't get the right serviceBean");
}
bean=(ServerFactoryBean)ctx.getBean("inlineSoapBinding");
assertNotNull(bean);
BindingConfiguration bc=bean.getBindingConfig();
assertTrue(bc instanceof SoapBindingConfiguration);
SoapBindingConfiguration sbc=(SoapBindingConfiguration)bc;
assertTrue(sbc.getVersion() instanceof Soap12);
bean=(ServerFactoryBean)ctx.getBean("simpleWithBindingId");
assertEquals("get the wrong BindingId",bean.getBindingId(),"http://cxf.apache.org/bindings/xformat");
bean=(ServerFactoryBean)ctx.getBean("simpleWithWSDL");
assertNotNull(bean);
assertEquals(bean.getWsdlLocation(),"org/apache/cxf/frontend/spring/simple.wsdl");
bean=(ServerFactoryBean)ctx.getBean("proxyBean");
assertNotNull(bean);
}
Class: org.apache.cxf.helpers.NameSpaceTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testNSStackOperations() throws Exception {
NSStack nsStackObj=new NSStack();
nsStackObj.push();
nsStackObj.add(MY_URL1);
nsStackObj.add(MY_OWN_PREFIX,MY_CUSTOM_URL);
nsStackObj.add(MY_URL2);
assertEquals(MY_URL1,nsStackObj.getURI("ns1"));
assertEquals(MY_CUSTOM_URL,nsStackObj.getURI(MY_OWN_PREFIX));
assertEquals(MY_URL2,nsStackObj.getURI("ns2"));
assertNull(nsStackObj.getURI("non-existent-prefix"));
assertEquals("ns2",nsStackObj.getPrefix(MY_URL2));
assertEquals(MY_OWN_PREFIX,nsStackObj.getPrefix(MY_CUSTOM_URL));
assertEquals("ns1",nsStackObj.getPrefix(MY_URL1));
assertNull(nsStackObj.getPrefix("non-existent-prefix"));
nsStackObj.pop();
assertNull(nsStackObj.getPrefix("non-existent-prefix"));
assertNull(nsStackObj.getPrefix(MY_CUSTOM_URL));
}
Class: org.apache.cxf.helpers.ServiceUtilsTest InternalCallVerifier EqualityVerifier
@Test public void testGetSchemaValidationType(){
for ( SchemaValidationType type : SchemaValidationType.values()) {
setupSchemaValidationValue(type.name(),false);
assertEquals(type,ServiceUtils.getSchemaValidationType(msg));
setupSchemaValidationValue(type.name().toLowerCase(),false);
assertEquals(type,ServiceUtils.getSchemaValidationType(msg));
setupSchemaValidationValue(StringUtils.capitalize(type.name()),false);
assertEquals(type,ServiceUtils.getSchemaValidationType(msg));
}
}
Class: org.apache.cxf.interceptor.LoggingOutInterceptorTest APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testCachedOutputStreamThreshold() throws Exception {
byte[] mex=" ".getBytes();
LoggingOutInterceptor p=new LoggingOutInterceptor();
p.setInMemThreshold(mex.length);
CachedOutputStream cos=handleAndGetCachedOutputStream(p);
cos.write(mex);
assertNull(cos.getTempFile());
cos.write("a".getBytes());
assertNotNull(cos.getTempFile());
}
Class: org.apache.cxf.interceptor.ServiceInvokerInterceptorTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testInterceptor() throws Exception {
ServiceInvokerInterceptor intc=new ServiceInvokerInterceptor();
MessageImpl m=new MessageImpl();
Exchange exchange=new ExchangeImpl();
m.setExchange(exchange);
exchange.setInMessage(m);
exchange.setOutMessage(new MessageImpl());
TestInvoker i=new TestInvoker();
Endpoint endpoint=createEndpoint(i);
exchange.put(Endpoint.class,endpoint);
Object input=new Object();
List lst=new ArrayList();
lst.add(input);
m.setContent(List.class,lst);
intc.handleMessage(m);
assertTrue(i.invoked);
List> list=exchange.getOutMessage().getContent(List.class);
assertEquals(input,list.get(0));
}
Class: org.apache.cxf.interceptor.security.DefaultSecurityContextTest BooleanVerifier InternalCallVerifier
@Test public void testUserInImplicitRoles(){
Subject s=new Subject();
Principal p=new SimplePrincipal("Barry");
s.getPrincipals().add(p);
Principal role=new SimplePrincipal("friend");
s.getPrincipals().add(role);
LoginSecurityContext context=new DefaultSecurityContext(p,s);
assertTrue(context.isUserInRole("friend"));
assertFalse(context.isUserInRole("family"));
assertFalse(context.isUserInRole("Barry"));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testMultipleRoles(){
Subject s=new Subject();
Principal p=new SimplePrincipal("Barry");
s.getPrincipals().add(p);
Set roles=new HashSet();
roles.add(new SimpleGroup("friend",p));
roles.add(new SimpleGroup("admin",p));
s.getPrincipals().addAll(roles);
LoginSecurityContext context=new DefaultSecurityContext(p,s);
assertTrue(context.isUserInRole("friend"));
assertTrue(context.isUserInRole("admin"));
assertFalse(context.isUserInRole("bar"));
Set roles2=context.getUserRoles();
assertEquals(roles2,roles);
}
Class: org.apache.cxf.interceptor.security.RolePrefixSecurityContextImplTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testMultipleRoles(){
Subject s=new Subject();
Principal p=new SimplePrincipal("Barry");
s.getPrincipals().add(p);
Set roles=new HashSet();
roles.add(new SimplePrincipal("role_friend"));
roles.add(new SimplePrincipal("role_admin"));
s.getPrincipals().addAll(roles);
LoginSecurityContext context=new RolePrefixSecurityContextImpl(s,"role_");
assertTrue(context.isUserInRole("role_friend"));
assertTrue(context.isUserInRole("role_admin"));
assertFalse(context.isUserInRole("role_bar"));
Set roles2=context.getUserRoles();
assertEquals(roles2,roles);
}
Class: org.apache.cxf.internal.CXFAPINamespaceHandlerTest InternalCallVerifier NullVerifier
@Test public void testGetSchemaLocation(){
CXFAPINamespaceHandler handler=new CXFAPINamespaceHandler();
assertNotNull(handler.getSchemaLocation("http://cxf.apache.org/configuration/beans"));
assertNotNull(handler.getSchemaLocation("http://cxf.apache.org/configuration/parameterized-types"));
assertNotNull(handler.getSchemaLocation("http://cxf.apache.org/configuration/security"));
assertNotNull(handler.getSchemaLocation("http://schemas.xmlsoap.org/wsdl/"));
assertNotNull(handler.getSchemaLocation("http://www.w3.org/2005/08/addressing"));
assertNotNull(handler.getSchemaLocation("http://schemas.xmlsoap.org/ws/2004/08/addressing"));
assertNotNull(handler.getSchemaLocation("http://cxf.apache.org/blueprint/core"));
}
Class: org.apache.cxf.javascript.BasicNameManagerTest InternalCallVerifier EqualityVerifier
@Test public void testPrefixGeneration(){
BasicNameManager manager=new BasicNameManager();
String jsp=manager.transformURI("http://ThisIsA.Test");
assertEquals("ThisIsA_Test",jsp);
jsp=manager.transformURI("uri:george.bill:fred");
assertEquals("george_bill_fred",jsp);
}
Class: org.apache.cxf.javascript.DocLitWrappedClientTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void callFunctionWithHeader(){
testUtilities.runInsideContext(Void.class,new JSRunnable(){
public Void run( Context context){
LOG.info("About to call testDummyHeader " + getAddress());
Notifier notifier=testUtilities.rhinoCallConvert("testDummyHeader",Notifier.class,testUtilities.javaToJS(getAddress()),testUtilities.javaToJS("narcissus"),null);
boolean notified=notifier.waitForJavascript(1000 * 10);
assertTrue(notified);
Integer errorStatus=testUtilities.rhinoEvaluateConvert("globalErrorStatus",Integer.class);
assertNull(errorStatus);
String errorText=testUtilities.rhinoEvaluateConvert("globalErrorStatusText",String.class);
assertNull(errorText);
Scriptable responseObject=(Scriptable)testUtilities.rhinoEvaluate("globalResponseObject");
assertNotNull(responseObject);
String returnValue=testUtilities.rhinoCallMethodInContext(String.class,responseObject,"getReturn");
assertEquals("narcissus",returnValue);
return null;
}
}
);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void inheritedProperties(){
testUtilities.runInsideContext(Void.class,new JSRunnable(){
public Void run( Context context){
Notifier notifier=testUtilities.rhinoCallConvert("testInheritance",Notifier.class,testUtilities.javaToJS(getAddress()));
boolean notified=notifier.waitForJavascript(1000 * 10);
assertTrue(notified);
SimpleDocLitWrappedImpl impl=(SimpleDocLitWrappedImpl)rawImplementor;
assertEquals("less",impl.getLastInheritanceTestDerived().getName());
return null;
}
}
);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void callIntReturnMethod(){
testUtilities.runInsideContext(Void.class,new JSRunnable(){
public Void run( Context context){
LOG.info("About to call test3/IntFunction" + getAddress());
Notifier notifier=testUtilities.rhinoCallConvert("test3",Notifier.class,testUtilities.javaToJS(getAddress()),testUtilities.javaToJS(Double.valueOf(17.0)),testUtilities.javaToJS(Float.valueOf((float)111.0)),testUtilities.javaToJS(Integer.valueOf(142)),testUtilities.javaToJS(Long.valueOf(1240000)),null);
boolean notified=notifier.waitForJavascript(1000 * 10);
assertTrue(notified);
Integer errorStatus=testUtilities.rhinoEvaluateConvert("globalErrorStatus",Integer.class);
assertNull(errorStatus);
String errorText=testUtilities.rhinoEvaluateConvert("globalErrorStatusText",String.class);
assertNull(errorText);
Scriptable responseObject=(Scriptable)testUtilities.rhinoEvaluate("globalResponseObject");
assertNotNull(responseObject);
int returnValue=testUtilities.rhinoCallMethodInContext(Integer.class,responseObject,"getReturn");
assertEquals(42,returnValue);
return null;
}
}
);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void callMethodWithWrappers(){
testUtilities.runInsideContext(Void.class,new JSRunnable(){
public Void run( Context context){
LOG.info("About to call test1 " + getAddress());
Notifier notifier=testUtilities.rhinoCallConvert("test1",Notifier.class,testUtilities.javaToJS(getAddress()),testUtilities.javaToJS(Double.valueOf(7.0)),testUtilities.javaToJS(Float.valueOf((float)11.0)),testUtilities.javaToJS(Integer.valueOf(42)),testUtilities.javaToJS(Long.valueOf(240000)),"This is the cereal shot from guns");
boolean notified=notifier.waitForJavascript(1000 * 10);
assertTrue(notified);
Integer errorStatus=testUtilities.rhinoEvaluateConvert("globalErrorStatus",Integer.class);
assertNull(errorStatus);
String errorText=testUtilities.rhinoEvaluateConvert("globalErrorStatusText",String.class);
assertNull(errorText);
Scriptable responseObject=(Scriptable)testUtilities.rhinoEvaluate("globalResponseObject");
assertNotNull(responseObject);
String returnString=testUtilities.rhinoCallMethodInContext(String.class,responseObject,"getReturnValue");
assertEquals("eels",returnString);
return null;
}
}
);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void callTest2WithNullString(){
testUtilities.runInsideContext(Void.class,new JSRunnable(){
public Void run( Context context){
LOG.info("About to call test2 with null string " + getAddress());
Notifier notifier=testUtilities.rhinoCallConvert("test2",Notifier.class,testUtilities.javaToJS(getAddress()),testUtilities.javaToJS(Double.valueOf(17.0)),testUtilities.javaToJS(Float.valueOf((float)111.0)),testUtilities.javaToJS(Integer.valueOf(142)),testUtilities.javaToJS(Long.valueOf(1240000)),null);
boolean notified=notifier.waitForJavascript(1000 * 10);
assertTrue(notified);
Integer errorStatus=testUtilities.rhinoEvaluateConvert("globalErrorStatus",Integer.class);
assertNull(errorStatus);
String errorText=testUtilities.rhinoEvaluateConvert("globalErrorStatusText",String.class);
assertNull(errorText);
Scriptable responseObject=(Scriptable)testUtilities.rhinoEvaluate("globalResponseObject");
assertNotNull(responseObject);
String returnString=testUtilities.rhinoCallMethodInContext(String.class,responseObject,"getReturn");
assertEquals("cetaceans",returnString);
return null;
}
}
);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void callMethodWithoutWrappers(){
testUtilities.runInsideContext(Void.class,new JSRunnable(){
public Void run( Context context){
LOG.info("About to call test2 " + getAddress());
Notifier notifier=testUtilities.rhinoCallConvert("test2",Notifier.class,testUtilities.javaToJS(getAddress()),testUtilities.javaToJS(Double.valueOf(17.0)),testUtilities.javaToJS(Float.valueOf((float)111.0)),testUtilities.javaToJS(Integer.valueOf(142)),testUtilities.javaToJS(Long.valueOf(1240000)),"This is the cereal shot from gnus");
boolean notified=notifier.waitForJavascript(1000 * 10);
assertTrue(notified);
Integer errorStatus=testUtilities.rhinoEvaluateConvert("globalErrorStatus",Integer.class);
assertNull(errorStatus);
String errorText=testUtilities.rhinoEvaluateConvert("globalErrorStatusText",String.class);
assertNull(errorText);
Scriptable responseObject=(Scriptable)testUtilities.rhinoEvaluate("globalResponseObject");
assertNotNull(responseObject);
String returnString=testUtilities.rhinoCallMethodInContext(String.class,responseObject,"getReturn");
assertEquals("cetaceans",returnString);
return null;
}
}
);
}
Class: org.apache.cxf.javascript.GenericAegisTest APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testGenerateJavascript() throws Exception {
GenericGenericClass impl=new GenericGenericClass();
ServerFactoryBean svrFactory=new ServerFactoryBean();
svrFactory.setServiceClass(impl.getClass());
svrFactory.setAddress("http://localhost:" + PORT + "/aegisgeneric");
svrFactory.setServiceBean(impl);
Server server=svrFactory.create();
ServiceInfo serviceInfo=((EndpointImpl)server.getEndpoint()).getEndpointInfo().getService();
Collection schemata=serviceInfo.getSchemas();
BasicNameManager nameManager=BasicNameManager.newNameManager(serviceInfo);
NamespacePrefixAccumulator prefixManager=new NamespacePrefixAccumulator(serviceInfo.getXmlSchemaCollection());
for ( SchemaInfo schema : schemata) {
SchemaJavascriptBuilder builder=new SchemaJavascriptBuilder(serviceInfo.getXmlSchemaCollection(),prefixManager,nameManager);
String allThatJavascript=builder.generateCodeForSchema(schema.getSchema());
assertNotNull(allThatJavascript);
}
ServiceJavascriptBuilder serviceBuilder=new ServiceJavascriptBuilder(serviceInfo,null,prefixManager,nameManager);
serviceBuilder.walk();
String serviceJavascript=serviceBuilder.getCode();
assertNotNull(serviceJavascript);
}
Class: org.apache.cxf.javascript.JsHttpRequestTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void runTests() throws Exception {
testUtilities.rhinoCallExpectingExceptionInContext("SYNTAX_ERR","testOpaqueURI");
testUtilities.rhinoCallExpectingExceptionInContext("SYNTAX_ERR","testNonAbsolute");
testUtilities.rhinoCallExpectingExceptionInContext("SYNTAX_ERR","testNonHttp");
testUtilities.rhinoCallExpectingExceptionInContext("INVALID_STATE_ERR","testSendNotOpenError");
testUtilities.rhinoCallInContext("testStateNotificationSync");
Notifier notifier=testUtilities.rhinoCallConvert("testAsyncHttpFetch1",Notifier.class);
testUtilities.rhinoCallInContext("testAsyncHttpFetch2");
boolean notified=notifier.waitForJavascript(2 * 10000);
assertTrue(notified);
assertEquals("HEADERS_RECEIVED",Boolean.TRUE,testUtilities.rhinoEvaluateConvert("asyncGotHeadersReceived",Boolean.class));
assertEquals("LOADING",Boolean.TRUE,testUtilities.rhinoEvaluateConvert("asyncGotLoading",Boolean.class));
assertEquals("DONE",Boolean.TRUE,testUtilities.rhinoEvaluateConvert("asyncGotDone",Boolean.class));
String outOfOrder=testUtilities.rhinoEvaluateConvert("outOfOrderError",String.class);
assertEquals("OutOfOrder",null,outOfOrder);
assertEquals("status 200",Integer.valueOf(200),testUtilities.rhinoEvaluateConvert("asyncStatus",Integer.class));
assertEquals("status text","OK",testUtilities.rhinoEvaluateConvert("asyncStatusText",String.class));
assertTrue("headers",testUtilities.rhinoEvaluateConvert("asyncResponseHeaders",String.class).contains("Content-Type: text/html"));
Object httpObj=testUtilities.rhinoCallInContext("testSyncHttpFetch");
assertNotNull(httpObj);
assertTrue(httpObj instanceof String);
String httpResponse=(String)httpObj;
assertTrue(httpResponse.contains("\u05e9\u05dc\u05d5\u05dd"));
Reader r=getResourceAsReader("/org/apache/cxf/javascript/XML_GreetMeDocLiteralReq.xml");
StringWriter writer=new StringWriter();
char[] buffer=new char[1024];
int readCount;
while ((readCount=r.read(buffer,0,1024)) > 0) {
writer.write(buffer,0,readCount);
}
String xml=writer.toString();
EndpointImpl endpoint=this.getBean(EndpointImpl.class,"greeter-service-endpoint");
JsSimpleDomNode xmlResponse=testUtilities.rhinoCallConvert("testSyncXml",JsSimpleDomNode.class,testUtilities.javaToJS(endpoint.getAddress()),testUtilities.javaToJS(xml));
assertNotNull(xmlResponse);
Document doc=(Document)xmlResponse.getWrappedNode();
testUtilities.addNamespace("t","http://apache.org/hello_world_xml_http/wrapped/types");
XPath textPath=XPathAssert.createXPath(testUtilities.getNamespaces());
String nodeText=(String)textPath.evaluate("//t:responseType/text()",doc,XPathConstants.STRING);
assertEquals("Hello \u05e9\u05dc\u05d5\u05dd",nodeText);
}
Class: org.apache.cxf.javascript.QueryHandlerTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void utilsTest() throws Exception {
URL endpointURL=new URL(dlbEndpoint.getEndpointInfo().getAddress() + "?js&nojsutils");
URLConnection connection=endpointURL.openConnection();
assertEquals("application/javascript;charset=UTF-8",connection.getContentType());
InputStream jsStream=connection.getInputStream();
String jsString=readStringFromStream(jsStream);
assertFalse(jsString.contains("function CxfApacheOrgUtil"));
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void dlbQueryTest() throws Exception {
LOG.finest("logged to avoid warning on LOG");
URL endpointURL=new URL(dlbEndpoint.getEndpointInfo().getAddress() + "?js");
URLConnection connection=endpointURL.openConnection();
assertEquals("application/javascript;charset=UTF-8",connection.getContentType());
InputStream jsStream=connection.getInputStream();
String js=readStringFromStream(jsStream);
assertNotSame("",js);
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier
@Test public void hwQueryTest() throws Exception {
URL endpointURL=new URL(hwEndpoint.getEndpointInfo().getAddress() + "?js");
String js=getStringFromURL(endpointURL);
assertNotSame(0,js.length());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@org.junit.Ignore @Test public void namespacePrefixTest() throws Exception {
URL endpointURL=new URL(hwgEndpoint.getEndpointInfo().getAddress() + "?js");
String js=getStringFromURL(endpointURL);
assertTrue(js.contains("hg_Greeter"));
}
Class: org.apache.cxf.javascript.types.AttributeTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test @org.junit.Ignore public void testSerialization() throws Exception {
setupClientAndRhino("simple-dlwu-proxy-factory");
testUtilities.readResourceIntoRhino("/serializationTests.js");
DataBinding dataBinding=clientProxyFactory.getServiceFactory().getDataBinding();
assertNotNull(dataBinding);
Object serialized=testUtilities.rhinoCallInContext("serializeTestBean1_1");
assertTrue(serialized instanceof String);
String xml=(String)serialized;
DataReader reader=dataBinding.createReader(XMLStreamReader.class);
StringReader stringReader=new StringReader(xml);
XMLStreamReader xmlStreamReader=xmlInputFactory.createXMLStreamReader(stringReader);
QName testBeanQName=new QName("uri:org.apache.cxf.javascript.testns","TestBean1");
Object bean=reader.read(testBeanQName,xmlStreamReader,TestBean1.class);
assertNotNull(bean);
assertTrue(bean instanceof TestBean1);
TestBean1 testBean=(TestBean1)bean;
assertEquals("bean1
Class: org.apache.cxf.javascript.types.SerializationTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSerialization() throws Exception {
setupClientAndRhino("simple-dlwu-proxy-factory");
testUtilities.readResourceIntoRhino("/serializationTests.js");
DataBinding dataBinding=clientProxyFactory.getServiceFactory().getDataBinding();
assertNotNull(dataBinding);
Object serialized=testUtilities.rhinoCallInContext("serializeTestBean1_1");
assertTrue(serialized instanceof String);
String xml=(String)serialized;
DataReader reader=dataBinding.createReader(XMLStreamReader.class);
StringReader stringReader=new StringReader(xml);
XMLStreamReader xmlStreamReader=xmlInputFactory.createXMLStreamReader(stringReader);
QName testBeanQName=new QName("uri:org.apache.cxf.javascript.testns","TestBean1");
Object bean=reader.read(testBeanQName,xmlStreamReader,TestBean1.class);
assertNotNull(bean);
assertTrue(bean instanceof TestBean1);
TestBean1 testBean=(TestBean1)bean;
assertEquals("bean1
Class: org.apache.cxf.jaxb.BareInInterceptorTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testInterceptorInbound() throws Exception {
setUpUsingHelloWorld();
BareInInterceptor interceptor=new BareInInterceptor();
message.setContent(XMLStreamReader.class,XMLInputFactory.newInstance().createXMLStreamReader(getTestStream(getClass(),"resources/GreetMeDocLiteralReq.xml")));
message.put(Message.INBOUND_MESSAGE,Message.INBOUND_MESSAGE);
interceptor.handleMessage(message);
assertNull(message.getContent(Exception.class));
List> parameters=message.getContent(List.class);
assertEquals(1,parameters.size());
Object obj=parameters.get(0);
assertTrue(obj instanceof GreetMe);
GreetMe greet=(GreetMe)obj;
assertEquals("TestSOAPInputPMessage",greet.getRequestType());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testInterceptorInbound1() throws Exception {
setUpUsingDocLit();
BareInInterceptor interceptor=new BareInInterceptor();
message.setContent(XMLStreamReader.class,XMLInputFactory.newInstance().createXMLStreamReader(getTestStream(getClass(),"resources/sayHiDocLitBareReq.xml")));
message.put(Message.INBOUND_MESSAGE,Message.INBOUND_MESSAGE);
interceptor.handleMessage(message);
assertNull(message.getContent(Exception.class));
List> parameters=message.getContent(List.class);
assertEquals(1,parameters.size());
Object obj=parameters.get(0);
assertTrue(obj instanceof TradePriceData);
TradePriceData greet=(TradePriceData)obj;
assertTrue(1.0 == greet.getTickerPrice());
assertEquals("CXF",greet.getTickerSymbol());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testInterceptorOutbound() throws Exception {
setUpUsingHelloWorld();
BareInInterceptor interceptor=new BareInInterceptor();
message.setContent(XMLStreamReader.class,XMLInputFactory.newInstance().createXMLStreamReader(getTestStream(getClass(),"resources/GreetMeDocLiteralResp.xml")));
message.put(Message.REQUESTOR_ROLE,Boolean.TRUE);
interceptor.handleMessage(message);
List> parameters=message.getContent(List.class);
assertEquals(1,parameters.size());
Object obj=parameters.get(0);
assertTrue(obj instanceof GreetMeResponse);
GreetMeResponse greet=(GreetMeResponse)obj;
assertEquals("TestSOAPOutputPMessage",greet.getResponseType());
}
InternalCallVerifier NullVerifier
@Test public void testInterceptorInboundBareNoParameter() throws Exception {
setUpUsingDocLit();
BareInInterceptor interceptor=new BareInInterceptor();
message.setContent(XMLStreamReader.class,XMLInputFactory.newInstance().createXMLStreamReader(getTestStream(getClass(),"resources/bareNoParamDocLitBareReq.xml")));
XMLStreamReader reader=message.getContent(XMLStreamReader.class);
StaxUtils.skipToStartOfElement(reader);
StaxUtils.nextEvent(reader);
message.put(Message.INBOUND_MESSAGE,Message.INBOUND_MESSAGE);
interceptor.handleMessage(message);
assertNull(message.getContent(Exception.class));
List> parameters=message.getContent(List.class);
assertNull(parameters);
}
Class: org.apache.cxf.jaxb.BareOutInterceptorTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testWriteInbound() throws Exception {
GreetMe greetMe=new GreetMe();
greetMe.setRequestType("requestType");
message.setContent(List.class,Arrays.asList(greetMe));
message.put(Message.REQUESTOR_ROLE,Boolean.TRUE);
interceptor.handleMessage(message);
writer.close();
assertNull(message.getContent(Exception.class));
ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
XMLStreamReader xr=StaxUtils.createXMLStreamReader(bais);
DepthXMLStreamReader reader=new DepthXMLStreamReader(xr);
StaxUtils.toNextElement(reader);
assertEquals(new QName("http://apache.org/hello_world_soap_http/types","greetMe"),reader.getName());
StaxUtils.nextEvent(reader);
StaxUtils.toNextElement(reader);
assertEquals(new QName("http://apache.org/hello_world_soap_http/types","requestType"),reader.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testWriteOutbound() throws Exception {
GreetMeResponse greetMe=new GreetMeResponse();
greetMe.setResponseType("responseType");
message.setContent(List.class,Arrays.asList(greetMe));
interceptor.handleMessage(message);
writer.close();
assertNull(message.getContent(Exception.class));
ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
XMLStreamReader xr=StaxUtils.createXMLStreamReader(bais);
DepthXMLStreamReader reader=new DepthXMLStreamReader(xr);
StaxUtils.toNextElement(reader);
assertEquals(new QName("http://apache.org/hello_world_soap_http/types","greetMeResponse"),reader.getName());
StaxUtils.nextEvent(reader);
StaxUtils.toNextElement(reader);
assertEquals(new QName("http://apache.org/hello_world_soap_http/types","responseType"),reader.getName());
}
Class: org.apache.cxf.jaxb.DataBindingMarshallerPropertiesTest BooleanVerifier InternalCallVerifier
@Test public void testInitializeUnmarshallerProperties() throws Exception {
JAXBDataBinding db=new JAXBDataBinding();
Map unmarshallerProperties=new HashMap();
unmarshallerProperties.put("someproperty","somevalue");
db.setUnmarshallerProperties(unmarshallerProperties);
db.initialize(service);
assertTrue("somevalue".equals(db.getUnmarshallerProperties().get("someproperty")));
}
Class: org.apache.cxf.jaxb.DocLiteralInInterceptorTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testInterceptorInboundBare() throws Exception {
setUpUsingDocLit();
DocLiteralInInterceptor interceptor=new DocLiteralInInterceptor();
message.setContent(XMLStreamReader.class,XMLInputFactory.newInstance().createXMLStreamReader(getTestStream(getClass(),"resources/sayHiDocLitBareReq.xml")));
XMLStreamReader reader=message.getContent(XMLStreamReader.class);
StaxUtils.skipToStartOfElement(reader);
message.put(Message.INBOUND_MESSAGE,Message.INBOUND_MESSAGE);
interceptor.handleMessage(message);
assertNull(message.getContent(Exception.class));
List> parameters=message.getContent(List.class);
assertEquals(1,parameters.size());
Object obj=parameters.get(0);
assertTrue(obj instanceof TradePriceData);
TradePriceData greet=(TradePriceData)obj;
assertTrue(1.0 == greet.getTickerPrice());
assertEquals("CXF",greet.getTickerSymbol());
}
InternalCallVerifier NullVerifier
@Test public void testInterceptorInboundBareNoParameter() throws Exception {
setUpUsingDocLit();
DocLiteralInInterceptor interceptor=new DocLiteralInInterceptor();
message.setContent(XMLStreamReader.class,XMLInputFactory.newInstance().createXMLStreamReader(getTestStream(getClass(),"resources/bareNoParamDocLitBareReq.xml")));
XMLStreamReader reader=message.getContent(XMLStreamReader.class);
StaxUtils.skipToStartOfElement(reader);
StaxUtils.nextEvent(reader);
message.put(Message.INBOUND_MESSAGE,Message.INBOUND_MESSAGE);
interceptor.handleMessage(message);
assertNull(message.getContent(Exception.class));
List> parameters=message.getContent(List.class);
assertNull(parameters);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testInterceptorInboundWrapped() throws Exception {
setUpUsingHelloWorld();
DocLiteralInInterceptor interceptor=new DocLiteralInInterceptor();
message.setContent(XMLStreamReader.class,XMLInputFactory.newInstance().createXMLStreamReader(getTestStream(getClass(),"resources/GreetMeDocLiteralReq.xml")));
XMLStreamReader reader=message.getContent(XMLStreamReader.class);
StaxUtils.skipToStartOfElement(reader);
message.put(Message.INBOUND_MESSAGE,Message.INBOUND_MESSAGE);
interceptor.handleMessage(message);
assertNull(message.getContent(Exception.class));
List> parameters=message.getContent(List.class);
assertEquals(1,parameters.size());
Object obj=parameters.get(0);
assertTrue(obj instanceof GreetMe);
GreetMe greet=(GreetMe)obj;
assertEquals("TestSOAPInputPMessage",greet.getRequestType());
}
Class: org.apache.cxf.jaxb.JAXBDataBindingTest InternalCallVerifier EqualityVerifier
@Test public void testExtraClass(){
Class>[] extraClass=new Class[]{GreetMe.class,GreetMeOneWay.class};
jaxbDataBinding.setExtraClass(extraClass);
assertEquals(jaxbDataBinding.getExtraClass().length,2);
assertEquals(jaxbDataBinding.getExtraClass()[0],GreetMe.class);
assertEquals(jaxbDataBinding.getExtraClass()[1],GreetMeOneWay.class);
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testCreateReader(){
DataReader> reader=jaxbDataBinding.createReader(XMLStreamReader.class);
assertTrue(reader instanceof DataReaderImpl);
reader=jaxbDataBinding.createReader(XMLEventReader.class);
assertTrue(reader instanceof DataReaderImpl);
reader=jaxbDataBinding.createReader(Node.class);
assertTrue(reader instanceof DataReaderImpl);
reader=jaxbDataBinding.createReader(null);
assertNull(reader);
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSupportedFormats(){
List> cls=Arrays.asList(jaxbDataBinding.getSupportedWriterFormats());
assertNotNull(cls);
assertEquals(4,cls.size());
assertTrue(cls.contains(XMLStreamWriter.class));
assertTrue(cls.contains(XMLEventWriter.class));
assertTrue(cls.contains(Node.class));
assertTrue(cls.contains(OutputStream.class));
cls=Arrays.asList(jaxbDataBinding.getSupportedReaderFormats());
assertNotNull(cls);
assertEquals(3,cls.size());
assertTrue(cls.contains(XMLStreamReader.class));
assertTrue(cls.contains(XMLEventReader.class));
assertTrue(cls.contains(Node.class));
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testCreateWriter(){
DataWriter> writer=jaxbDataBinding.createWriter(XMLStreamWriter.class);
assertTrue(writer instanceof DataWriterImpl);
writer=jaxbDataBinding.createWriter(XMLEventWriter.class);
assertTrue(writer instanceof DataWriterImpl);
writer=jaxbDataBinding.createWriter(Node.class);
assertTrue(writer instanceof DataWriterImpl);
writer=jaxbDataBinding.createWriter(null);
assertNull(writer);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testConfiguredXmlAdapter() throws Exception {
Language dutch=new Language("nl_NL","Dutch");
Language americanEnglish=new Language("en_US","Americanish");
Person person=new Person(dutch);
JAXBDataBinding binding=new JAXBDataBinding(Person.class,Language.class);
binding.setConfiguredXmlAdapters(Arrays.>asList(new LanguageAdapter(dutch,americanEnglish)));
DataWriter writer=binding.createWriter(OutputStream.class);
ByteArrayOutputStream baos=new ByteArrayOutputStream();
writer.write(person,baos);
String output=baos.toString();
String xml="";
assertEquals(xml,output);
DataReader reader=binding.createReader(XMLStreamReader.class);
Person read=(Person)reader.read(XMLInputFactory.newFactory().createXMLStreamReader(new StringReader(xml)));
assertEquals(dutch,read.getMotherTongue());
}
Class: org.apache.cxf.jaxb.JAXBEncoderDecoderTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testMarshallIntoStaxEventWriter() throws Exception {
GreetMe obj=new GreetMe();
obj.setRequestType("Hello");
QName elName=new QName(wrapperAnnotation.targetNamespace(),wrapperAnnotation.localName());
MessagePartInfo part=new MessagePartInfo(elName,null);
part.setElement(true);
part.setElementQName(elName);
ByteArrayOutputStream baos=new ByteArrayOutputStream();
XMLOutputFactory opFactory=XMLOutputFactory.newInstance();
opFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES,Boolean.TRUE);
FixNamespacesXMLEventWriter writer=new FixNamespacesXMLEventWriter(opFactory.createXMLEventWriter(baos));
assertNull(writer.getMarshaller());
Marshaller m=context.createMarshaller();
JAXBEncoderDecoder.marshall(m,obj,part,writer);
assertEquals(m,writer.getMarshaller());
writer.flush();
writer.close();
ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
XMLInputFactory ipFactory=XMLInputFactory.newInstance();
XMLEventReader reader=ipFactory.createXMLEventReader(bais);
Unmarshaller um=context.createUnmarshaller();
Object val=um.unmarshal(reader,GreetMe.class);
assertTrue(val instanceof JAXBElement);
val=((JAXBElement>)val).getValue();
assertTrue(val instanceof GreetMe);
assertEquals(obj.getRequestType(),((GreetMe)val).getRequestType());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testMarshallIntoStaxStreamWriter() throws Exception {
GreetMe obj=new GreetMe();
obj.setRequestType("Hello");
QName elName=new QName(wrapperAnnotation.targetNamespace(),wrapperAnnotation.localName());
MessagePartInfo part=new MessagePartInfo(elName,null);
part.setElement(true);
part.setElementQName(elName);
ByteArrayOutputStream baos=new ByteArrayOutputStream();
XMLOutputFactory opFactory=XMLOutputFactory.newInstance();
opFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES,Boolean.TRUE);
FixNamespacesXMLStreamWriter writer=new FixNamespacesXMLStreamWriter(opFactory.createXMLStreamWriter(baos));
assertNull(writer.getMarshaller());
Marshaller m=context.createMarshaller();
JAXBEncoderDecoder.marshall(m,obj,part,writer);
assertEquals(m,writer.getMarshaller());
writer.flush();
writer.close();
ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
XMLInputFactory ipFactory=XMLInputFactory.newInstance();
XMLEventReader reader=ipFactory.createXMLEventReader(bais);
Unmarshaller um=context.createUnmarshaller();
Object val=um.unmarshal(reader,GreetMe.class);
assertTrue(val instanceof JAXBElement);
val=((JAXBElement>)val).getValue();
assertTrue(val instanceof GreetMe);
assertEquals(obj.getRequestType(),((GreetMe)val).getRequestType());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testUnmarshallFromStaxStreamReader() throws Exception {
QName elName=new QName(wrapperAnnotation.targetNamespace(),wrapperAnnotation.localName());
MessagePartInfo part=new MessagePartInfo(elName,null);
InputStream is=getClass().getResourceAsStream("resources/GreetMeDocLiteralReq.xml");
XMLInputFactory factory=XMLInputFactory.newInstance();
XMLStreamReader reader=factory.createXMLStreamReader(is);
QName[] tags={SOAP_ENV,SOAP_BODY};
StaxStreamFilter filter=new StaxStreamFilter(tags);
FixNamespacesXMLStreamReader filteredReader=new FixNamespacesXMLStreamReader(factory.createFilteredReader(reader,filter));
assertNull(filteredReader.getUnmarshaller());
part.setTypeClass(GreetMe.class);
Unmarshaller um=context.createUnmarshaller();
Object val=JAXBEncoderDecoder.unmarshall(um,filteredReader,part,true);
assertEquals(um,filteredReader.getUnmarshaller());
assertNotNull(val);
assertTrue(val instanceof GreetMe);
assertEquals("TestSOAPInputPMessage",((GreetMe)val).getRequestType());
is.close();
}
InternalCallVerifier NullVerifier
@Test public void testDefaultValueConverter() throws Exception {
Base64WithDefaultValueType testData=(new ObjectFactory()).createBase64WithDefaultValueType();
byte[] checkValue=testData.getAttributeWithDefaultValue();
assertNotNull(checkValue);
}
APIUtilityVerifier UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testMarshallIntoDOM() throws Exception {
String str=new String("Hello");
QName inCorrectElName=new QName("http://test_jaxb_marshall","requestType");
MessagePartInfo part=new MessagePartInfo(inCorrectElName,null);
part.setElement(true);
part.setElementQName(inCorrectElName);
Document doc=DOMUtils.createDocument();
Element elNode=doc.createElementNS(inCorrectElName.getNamespaceURI(),inCorrectElName.getLocalPart());
assertNotNull(elNode);
Node node;
try {
JAXBEncoderDecoder.marshall(context.createMarshaller(),null,part,elNode);
fail("Should have thrown a Fault");
}
catch ( Fault ex) {
}
GreetMe obj=new GreetMe();
obj.setRequestType("Hello");
QName elName=new QName(wrapperAnnotation.targetNamespace(),wrapperAnnotation.localName());
part.setElementQName(elName);
JAXBEncoderDecoder.marshall(context.createMarshaller(),obj,part,elNode);
node=elNode.getLastChild();
assertEquals(Node.ELEMENT_NODE,node.getNodeType());
Node childNode=node.getFirstChild();
assertEquals(Node.ELEMENT_NODE,childNode.getNodeType());
childNode=childNode.getFirstChild();
assertEquals(Node.TEXT_NODE,childNode.getNodeType());
assertEquals(str,childNode.getNodeValue());
StringStruct stringStruct=new StringStruct();
stringStruct.setArg1("world");
JAXBEncoderDecoder.marshall(context.createMarshaller(),stringStruct,part,elNode);
try {
Marshaller m=context.createMarshaller();
m.setSchema(schema);
JAXBEncoderDecoder.marshall(m,stringStruct,part,elNode);
fail("Marshal with schema should have thrown a Fault");
}
catch ( Fault ex) {
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testMarshallWithoutQNameInfo() throws Exception {
GreetMe obj=new GreetMe();
obj.setRequestType("Hello");
ByteArrayOutputStream baos=new ByteArrayOutputStream();
XMLOutputFactory opFactory=XMLOutputFactory.newInstance();
opFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES,Boolean.TRUE);
XMLEventWriter writer=opFactory.createXMLEventWriter(baos);
JAXBEncoderDecoder.marshall(context.createMarshaller(),obj,null,writer);
writer.flush();
writer.close();
ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
XMLInputFactory ipFactory=XMLInputFactory.newInstance();
XMLEventReader reader=ipFactory.createXMLEventReader(bais);
Unmarshaller um=context.createUnmarshaller();
Object val=um.unmarshal(reader,GreetMe.class);
assertTrue(val instanceof JAXBElement);
val=((JAXBElement>)val).getValue();
assertTrue(val instanceof GreetMe);
assertEquals(obj.getRequestType(),((GreetMe)val).getRequestType());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testUnmarshallWithoutClzInfo() throws Exception {
QName elName=new QName(wrapperAnnotation.targetNamespace(),wrapperAnnotation.localName());
Document doc=DOMUtils.createDocument();
Element elNode=doc.createElementNS(elName.getNamespaceURI(),elName.getLocalPart());
Element rtEl=doc.createElementNS(elName.getNamespaceURI(),"requestType");
elNode.appendChild(rtEl);
rtEl.appendChild(doc.createTextNode("Hello Test"));
Object obj=JAXBEncoderDecoder.unmarshall(context.createUnmarshaller(),elNode,null,true);
assertNotNull(obj);
assertEquals(GreetMe.class,obj.getClass());
assertEquals("Hello Test",((GreetMe)obj).getRequestType());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testMarshalRPCLit() throws Exception {
QName elName=new QName("http://test_jaxb_marshall","in");
MessagePartInfo part=new MessagePartInfo(elName,null);
part.setElement(true);
part.setElementQName(elName);
Document doc=DOMUtils.createDocument();
Element elNode=doc.createElementNS(elName.getNamespaceURI(),elName.getLocalPart());
JAXBEncoderDecoder.marshall(context.createMarshaller(),new String("TestSOAPMessage"),part,elNode);
assertEquals("TestSOAPMessage",elNode.getFirstChild().getFirstChild().getNodeValue());
}
APIUtilityVerifier UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testUnMarshall() throws Exception {
QName elName=new QName(wrapperAnnotation.targetNamespace(),wrapperAnnotation.localName());
MessagePartInfo part=new MessagePartInfo(elName,null);
part.setElement(true);
part.setElementQName(elName);
part.setTypeClass(Class.forName(wrapperAnnotation.className()));
Document doc=DOMUtils.createDocument();
Element elNode=doc.createElementNS(elName.getNamespaceURI(),elName.getLocalPart());
Element rtEl=doc.createElementNS(elName.getNamespaceURI(),"requestType");
elNode.appendChild(rtEl);
rtEl.appendChild(doc.createTextNode("Hello Test"));
Object obj=JAXBEncoderDecoder.unmarshall(context.createUnmarshaller(),elNode,part,true);
assertNotNull(obj);
assertEquals(GreetMe.class,obj.getClass());
assertEquals("Hello Test",((GreetMe)obj).getRequestType());
part.setTypeClass(String.class);
Node n=null;
try {
JAXBEncoderDecoder.unmarshall(context.createUnmarshaller(),n,part,true);
fail("Should have received a Fault");
}
catch ( Fault pe) {
}
catch ( Exception ex) {
fail("Should have received a Fault, not: " + ex);
}
elName=new QName(wrapperAnnotation.targetNamespace(),"stringStruct");
part=new MessagePartInfo(elName,null);
part.setElement(true);
part.setElementQName(elName);
part.setTypeClass(Class.forName("org.apache.hello_world_soap_http.types.StringStruct"));
doc=DOMUtils.createDocument();
elNode=doc.createElementNS(elName.getNamespaceURI(),elName.getLocalPart());
rtEl=doc.createElementNS(elName.getNamespaceURI(),"arg1");
elNode.appendChild(rtEl);
rtEl.appendChild(doc.createTextNode("World"));
obj=JAXBEncoderDecoder.unmarshall(context.createUnmarshaller(),elNode,part,true);
assertNotNull(obj);
assertEquals(StringStruct.class,obj.getClass());
assertEquals("World",((StringStruct)obj).getArg1());
try {
Unmarshaller m=context.createUnmarshaller();
m.setSchema(schema);
obj=JAXBEncoderDecoder.unmarshall(m,elNode,part,true);
fail("Should have thrown a Fault");
}
catch ( Fault ex) {
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testUnmarshallFromStaxEventReader() throws Exception {
QName elName=new QName(wrapperAnnotation.targetNamespace(),wrapperAnnotation.localName());
MessagePartInfo part=new MessagePartInfo(elName,null);
InputStream is=getClass().getResourceAsStream("resources/GreetMeDocLiteralReq.xml");
XMLInputFactory factory=XMLInputFactory.newInstance();
FixNamespacesXMLEventReader reader=new FixNamespacesXMLEventReader(factory.createXMLEventReader(is));
assertNull(reader.getUnmarshaller());
part.setTypeClass(GreetMe.class);
Unmarshaller um=context.createUnmarshaller();
Object val=JAXBEncoderDecoder.unmarshall(um,reader,part,true);
assertEquals(um,reader.getUnmarshaller());
assertNotNull(val);
assertTrue(val instanceof GreetMe);
assertEquals("TestSOAPInputPMessage",((GreetMe)val).getRequestType());
is.close();
}
Class: org.apache.cxf.jaxb.JAXBWrapperHelperTest BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void getBooleanTypeWrappedPart() throws Exception {
SetIsOK ok=new SetIsOK();
ok.setParameter3(new boolean[]{true,false});
ok.setParameter4("hello");
List partNames=Arrays.asList(new String[]{"Parameter1","Parameter2","Parameter3","Parameter4","Parameter5"});
List elTypeNames=Arrays.asList(new String[]{"boolean","int","boolean","string","string"});
List> partClasses=Arrays.asList(new Class>[]{Boolean.TYPE,Integer.TYPE,boolean[].class,String.class,List.class});
WrapperHelper wh=new JAXBDataBinding().createWrapperHelper(SetIsOK.class,null,partNames,elTypeNames,partClasses);
List lst=wh.getWrapperParts(ok);
assertEquals(5,lst.size());
assertTrue(lst.get(0) instanceof Boolean);
assertTrue(lst.get(1) instanceof Integer);
assertTrue(lst.get(2) instanceof boolean[]);
assertTrue(((boolean[])lst.get(2))[0]);
assertFalse(((boolean[])lst.get(2))[1]);
assertEquals("hello",lst.get(3));
lst.set(0,Boolean.TRUE);
Object o=wh.createWrapperObject(lst);
assertNotNull(0);
ok=(SetIsOK)o;
assertTrue(ok.isParameter1());
assertTrue(ok.getParameter3()[0]);
assertFalse(ok.getParameter3()[1]);
assertEquals("hello",ok.getParameter4());
}
Class: org.apache.cxf.jaxb.io.XMLStreamDataReaderTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testSetProperty() throws Exception {
MyCustomHandler handler=new MyCustomHandler();
DataReaderImpl dr=newDataReader(handler);
Object val=dr.read(reader);
assertTrue(val instanceof GreetMe);
assertEquals("TestSOAPInputPMessage",((GreetMe)val).getRequestType());
assertTrue(handler.getUsed());
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testReadBare() throws Exception {
JAXBDataBinding db=getDataBinding(TradePriceData.class);
reader=getTestReader("../resources/sayHiDocLitBareReq.xml");
assertNotNull(reader);
DataReader dr=db.createReader(XMLStreamReader.class);
assertNotNull(dr);
QName elName=new QName("http://apache.org/hello_world_doc_lit_bare/types","inout");
MessagePartInfo part=new MessagePartInfo(elName,null);
part.setElement(true);
part.setElementQName(elName);
part.setTypeClass(TradePriceData.class);
Object val=dr.read(part,reader);
assertNotNull(val);
assertTrue(val instanceof TradePriceData);
assertEquals("CXF",((TradePriceData)val).getTickerSymbol());
assertEquals(new Float(1.0f),new Float(((TradePriceData)val).getTickerPrice()));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testReadRPC() throws Exception {
JAXBDataBinding db=getDataBinding(MyComplexStruct.class);
QName[] tags={new QName("http://apache.org/hello_world_rpclit","sendReceiveData")};
reader=getTestReader("../resources/greetMeRpcLitReq.xml");
assertNotNull(reader);
XMLStreamReader localReader=getTestFilteredReader(reader,tags);
DataReader dr=db.createReader(XMLStreamReader.class);
assertNotNull(dr);
Object val=dr.read(new QName("http://apache.org/hello_world_rpclit","in"),localReader,MyComplexStruct.class);
assertNotNull(val);
assertTrue(val instanceof MyComplexStruct);
assertEquals("this is element 1",((MyComplexStruct)val).getElem1());
assertEquals("this is element 2",((MyComplexStruct)val).getElem2());
assertEquals(42,((MyComplexStruct)val).getElem3());
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testReadWrapperReturn() throws Exception {
JAXBDataBinding db=getDataBinding(GreetMeResponse.class);
reader=getTestReader("../resources/GreetMeDocLiteralResp.xml");
assertNotNull(reader);
DataReader dr=db.createReader(XMLStreamReader.class);
assertNotNull(dr);
Object retValue=dr.read(reader);
assertNotNull(retValue);
assertTrue(retValue instanceof GreetMeResponse);
assertEquals("TestSOAPOutputPMessage",((GreetMeResponse)retValue).getResponseType());
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testReadWrapper() throws Exception {
JAXBDataBinding db=getDataBinding(GreetMe.class);
reader=getTestReader("../resources/GreetMeDocLiteralReq.xml");
assertNotNull(reader);
DataReader dr=db.createReader(XMLStreamReader.class);
assertNotNull(dr);
Object val=dr.read(reader);
assertNotNull(val);
assertTrue(val instanceof GreetMe);
assertEquals("TestSOAPInputPMessage",((GreetMe)val).getRequestType());
}
UtilityVerifier BooleanVerifier InternalCallVerifier HybridVerifier
@Test public void testSetPropertyWithCustomExceptionHandling() throws Exception {
MyCustomMarshallerHandler handler=new MyCustomMarshallerHandler();
DataReaderImpl dr=newDataReader(handler);
try {
dr.read(reader);
fail("Expected exception");
}
catch ( Fault f) {
assertTrue(f.getMessage().contains("My unmarshalling exception"));
}
assertTrue(handler.getUsed());
assertFalse(handler.isOnMarshalComplete());
assertTrue(handler.isOnUnmarshalComplete());
}
Class: org.apache.cxf.jaxb.io.XMLStreamDataWriterTest APIUtilityVerifier BranchVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testWriteWithContextualNamespaceDecls() throws Exception {
JAXBDataBinding db=getTestWriterFactory(GreetMe.class);
Map nspref=new HashMap();
nspref.put("http://apache.org/hello_world_soap_http/types","x");
db.setNamespaceMap(nspref);
db.setContextualNamespaceMap(nspref);
DataWriter dw=db.createWriter(OutputStream.class);
assertNotNull(dw);
GreetMe val=new GreetMe();
val.setRequestType("Hello");
dw.write(val,baos);
String xstr=new String(baos.toByteArray());
if (!db.getContext().getClass().getName().contains("eclipse")) {
assertEquals("Hello ",xstr);
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testWriteBare() throws Exception {
JAXBDataBinding db=getTestWriterFactory(TradePriceData.class);
DataWriter dw=db.createWriter(XMLStreamWriter.class);
assertNotNull(dw);
TradePriceData val=new TradePriceData();
val.setTickerSymbol("This is a symbol");
val.setTickerPrice(1.0f);
QName elName=new QName("http://apache.org/hello_world_doc_lit_bare/types","inout");
MessagePartInfo part=new MessagePartInfo(elName,null);
part.setElement(true);
part.setElementQName(elName);
dw.write(val,part,streamWriter);
streamWriter.flush();
ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
XMLStreamReader xr=inFactory.createXMLStreamReader(bais);
DepthXMLStreamReader reader=new DepthXMLStreamReader(xr);
StaxUtils.toNextElement(reader);
assertEquals(new QName("http://apache.org/hello_world_doc_lit_bare/types","inout"),reader.getName());
StaxUtils.nextEvent(reader);
StaxUtils.toNextElement(reader);
assertEquals(new QName("http://apache.org/hello_world_doc_lit_bare/types","tickerSymbol"),reader.getName());
StaxUtils.nextEvent(reader);
StaxUtils.toNextText(reader);
assertEquals("This is a symbol",reader.getText());
}
UtilityVerifier BooleanVerifier InternalCallVerifier HybridVerifier
@Test public void testSetPropertyWithCustomExceptionHandling() throws Exception {
MyCustomMarshallerHandler handler=new MyCustomMarshallerHandler();
DataWriterImpl dw=newDataWriter(handler);
TradePriceData val=new TradePriceData();
val.setTickerSymbol("This is a symbol");
val.setTickerPrice(1.0f);
QName elName=new QName("http://apache.org/hello_world_doc_lit_bare/types","inout");
MessagePartInfo part=new MessagePartInfo(elName,null);
part.setElement(true);
part.setElementQName(elName);
try {
dw.write(val,part,streamWriter);
streamWriter.flush();
fail("Expected exception");
}
catch ( Fault f) {
assertTrue(f.getMessage().contains("My marshalling exception"));
}
assertTrue(handler.getUsed());
assertTrue(handler.isOnMarshalComplete());
assertFalse(handler.isOnUnmarshalComplete());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testWriteWithNamespacePrefixMapping() throws Exception {
JAXBDataBinding db=getTestWriterFactory(GreetMe.class);
Map nspref=new HashMap();
nspref.put("http://apache.org/hello_world_soap_http/types","x");
db.setNamespaceMap(nspref);
DataWriter dw=db.createWriter(OutputStream.class);
assertNotNull(dw);
GreetMe val=new GreetMe();
val.setRequestType("Hello");
dw.write(val,baos);
ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
XMLStreamReader xr=inFactory.createXMLStreamReader(bais);
DepthXMLStreamReader reader=new DepthXMLStreamReader(xr);
StaxUtils.toNextElement(reader);
QName qname=reader.getName();
assertEquals(new QName("http://apache.org/hello_world_soap_http/types","greetMe"),qname);
assertEquals("x",qname.getPrefix());
assertEquals(1,reader.getNamespaceCount());
assertEquals("http://apache.org/hello_world_soap_http/types",reader.getNamespaceURI(0));
assertEquals("x",reader.getNamespacePrefix(0));
StaxUtils.nextEvent(reader);
StaxUtils.toNextElement(reader);
qname=reader.getName();
assertEquals(new QName("http://apache.org/hello_world_soap_http/types","requestType"),qname);
assertEquals("x",qname.getPrefix());
StaxUtils.nextEvent(reader);
StaxUtils.toNextText(reader);
assertEquals("Hello",reader.getText());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testWriteWrapperReturn() throws Exception {
JAXBDataBinding db=getTestWriterFactory(GreetMeResponse.class);
DataWriter dw=db.createWriter(XMLStreamWriter.class);
assertNotNull(dw);
GreetMeResponse retVal=new GreetMeResponse();
retVal.setResponseType("TESTOUTPUTMESSAGE");
dw.write(retVal,streamWriter);
streamWriter.flush();
ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
XMLStreamReader xr=inFactory.createXMLStreamReader(bais);
DepthXMLStreamReader reader=new DepthXMLStreamReader(xr);
StaxUtils.toNextElement(reader);
assertEquals(new QName("http://apache.org/hello_world_soap_http/types","greetMeResponse"),reader.getName());
StaxUtils.nextEvent(reader);
StaxUtils.toNextElement(reader);
assertEquals(new QName("http://apache.org/hello_world_soap_http/types","responseType"),reader.getName());
StaxUtils.nextEvent(reader);
StaxUtils.toNextText(reader);
assertEquals("TESTOUTPUTMESSAGE",reader.getText());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testWriteRPCLit1() throws Exception {
JAXBDataBinding db=getTestWriterFactory();
DataWriter dw=db.createWriter(XMLStreamWriter.class);
assertNotNull(dw);
String val=new String("TESTOUTPUTMESSAGE");
QName elName=new QName("http://apache.org/hello_world_rpclit/types","in");
MessagePartInfo part=new MessagePartInfo(elName,null);
part.setElement(true);
part.setElementQName(elName);
dw.write(val,part,streamWriter);
streamWriter.flush();
ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
XMLStreamReader xr=inFactory.createXMLStreamReader(bais);
DepthXMLStreamReader reader=new DepthXMLStreamReader(xr);
StaxUtils.toNextElement(reader);
assertEquals(new QName("http://apache.org/hello_world_rpclit/types","in"),reader.getName());
StaxUtils.nextEvent(reader);
StaxUtils.toNextText(reader);
assertEquals("TESTOUTPUTMESSAGE",reader.getText());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testWriteRPCLit2() throws Exception {
JAXBDataBinding db=getTestWriterFactory(MyComplexStruct.class);
DataWriter dw=db.createWriter(XMLStreamWriter.class);
assertNotNull(dw);
MyComplexStruct val=new MyComplexStruct();
val.setElem1("This is element 1");
val.setElem2("This is element 2");
val.setElem3(1);
QName elName=new QName("http://apache.org/hello_world_rpclit/types","in");
MessagePartInfo part=new MessagePartInfo(elName,null);
part.setElement(true);
part.setElementQName(elName);
dw.write(val,part,streamWriter);
streamWriter.flush();
ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
XMLStreamReader xr=inFactory.createXMLStreamReader(bais);
DepthXMLStreamReader reader=new DepthXMLStreamReader(xr);
StaxUtils.toNextElement(reader);
assertEquals(new QName("http://apache.org/hello_world_rpclit/types","in"),reader.getName());
StaxUtils.nextEvent(reader);
StaxUtils.toNextElement(reader);
assertEquals(new QName("http://apache.org/hello_world_rpclit/types","elem1"),reader.getName());
StaxUtils.nextEvent(reader);
StaxUtils.toNextText(reader);
assertEquals("This is element 1",reader.getText());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testWriteWrapper() throws Exception {
JAXBDataBinding db=getTestWriterFactory(GreetMe.class);
DataWriter dw=db.createWriter(XMLStreamWriter.class);
assertNotNull(dw);
GreetMe val=new GreetMe();
val.setRequestType("Hello");
dw.write(val,streamWriter);
streamWriter.flush();
ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
XMLStreamReader xr=inFactory.createXMLStreamReader(bais);
DepthXMLStreamReader reader=new DepthXMLStreamReader(xr);
StaxUtils.toNextElement(reader);
assertEquals(new QName("http://apache.org/hello_world_soap_http/types","greetMe"),reader.getName());
StaxUtils.nextEvent(reader);
StaxUtils.toNextElement(reader);
assertEquals(new QName("http://apache.org/hello_world_soap_http/types","requestType"),reader.getName());
StaxUtils.nextEvent(reader);
StaxUtils.toNextText(reader);
assertEquals("Hello",reader.getText());
}
Class: org.apache.cxf.jaxrs.JAXRSServerFactoryBeanTest InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testRegisterProviders(){
JAXRSServerFactoryBean bean=new JAXRSServerFactoryBean();
bean.setAddress("http://localhost:8080/rest");
bean.setStart(false);
bean.setResourceClasses(BookStore.class);
List providers=new ArrayList();
Object provider1=new CustomExceptionMapper();
providers.add(provider1);
Object provider2=new RuntimeExceptionMapper();
providers.add(provider2);
bean.setProviders(providers);
Server s=bean.create();
ServerProviderFactory factory=(ServerProviderFactory)s.getEndpoint().get(ServerProviderFactory.class.getName());
ExceptionMapper mapper1=factory.createExceptionMapper(Exception.class,new MessageImpl());
assertNotNull(mapper1);
ExceptionMapper mapper2=factory.createExceptionMapper(RuntimeException.class,new MessageImpl());
assertNotNull(mapper2);
assertNotSame(mapper1,mapper2);
assertSame(provider1,mapper1);
assertSame(provider2,mapper2);
}
Class: org.apache.cxf.jaxrs.JAXRSServiceFactoryBeanTest InternalCallVerifier EqualityVerifier
@Test public void testSubresourcesOnlyDynamicResolution() throws Exception {
JAXRSServiceFactoryBean sf=new JAXRSServiceFactoryBean();
sf.setResourceClasses(org.apache.cxf.jaxrs.resources.BookStoreSubresourcesOnly.class);
sf.create();
List resources=((JAXRSServiceImpl)sf.getService()).getClassResourceInfos();
assertEquals(1,resources.size());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testNoSubResources() throws Exception {
JAXRSServiceFactoryBean sf=new JAXRSServiceFactoryBean();
sf.setEnableStaticResolution(true);
sf.setResourceClasses(org.apache.cxf.jaxrs.resources.BookStoreNoSubResource.class);
sf.create();
List resources=((JAXRSServiceImpl)sf.getService()).getClassResourceInfos();
assertEquals(1,resources.size());
ClassResourceInfo rootCri=resources.get(0);
assertNotNull(rootCri.getURITemplate());
URITemplate template=rootCri.getURITemplate();
MultivaluedMap values=new MetadataMap();
assertTrue(template.match("/bookstore/books/123",values));
assertFalse(rootCri.hasSubResources());
MethodDispatcher md=rootCri.getMethodDispatcher();
assertEquals(7,md.getOperationResourceInfos().size());
Set ops=md.getOperationResourceInfos();
assertTrue("No operation found",verifyOp(ops,"getBook","GET",false));
assertTrue("No operation found",verifyOp(ops,"getBookStoreInfo","GET",false));
assertTrue("No operation found",verifyOp(ops,"getBooks","GET",false));
assertTrue("No operation found",verifyOp(ops,"getBookJSON","GET",false));
assertTrue("No operation found",verifyOp(ops,"addBook","POST",false));
assertTrue("No operation found",verifyOp(ops,"updateBook","PUT",false));
assertTrue("No operation found",verifyOp(ops,"deleteBook","DELETE",false));
}
APIUtilityVerifier BranchVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSubResources() throws Exception {
JAXRSServiceFactoryBean sf=new JAXRSServiceFactoryBean();
sf.setEnableStaticResolution(true);
sf.setResourceClasses(org.apache.cxf.jaxrs.resources.BookStore.class);
sf.create();
List resources=((JAXRSServiceImpl)sf.getService()).getClassResourceInfos();
assertEquals(1,resources.size());
ClassResourceInfo rootCri=resources.get(0);
assertNotNull(rootCri.getURITemplate());
URITemplate template=rootCri.getURITemplate();
MultivaluedMap values=new MetadataMap();
assertTrue(template.match("/bookstore/books/123",values));
assertTrue(rootCri.hasSubResources());
MethodDispatcher md=rootCri.getMethodDispatcher();
assertEquals(7,md.getOperationResourceInfos().size());
for ( OperationResourceInfo ori : md.getOperationResourceInfos()) {
if ("getDescription".equals(ori.getMethodToInvoke().getName())) {
assertEquals("GET",ori.getHttpMethod());
assertEquals("/path",ori.getURITemplate().getValue());
assertEquals("text/bar",ori.getProduceTypes().get(0).toString());
assertEquals("text/foo",ori.getConsumeTypes().get(0).toString());
assertFalse(ori.isSubResourceLocator());
}
else if ("getAuthor".equals(ori.getMethodToInvoke().getName())) {
assertEquals("GET",ori.getHttpMethod());
assertEquals("/path2",ori.getURITemplate().getValue());
assertEquals("text/bar2",ori.getProduceTypes().get(0).toString());
assertEquals("text/foo2",ori.getConsumeTypes().get(0).toString());
assertFalse(ori.isSubResourceLocator());
}
else if ("getBook".equals(ori.getMethodToInvoke().getName())) {
assertNull(ori.getHttpMethod());
assertNotNull(ori.getURITemplate());
assertTrue(ori.isSubResourceLocator());
}
else if ("getNewBook".equals(ori.getMethodToInvoke().getName())) {
assertNull(ori.getHttpMethod());
assertNotNull(ori.getURITemplate());
assertTrue(ori.isSubResourceLocator());
}
else if ("addBook".equals(ori.getMethodToInvoke().getName())) {
assertEquals("POST",ori.getHttpMethod());
assertNotNull(ori.getURITemplate());
assertFalse(ori.isSubResourceLocator());
}
else if ("updateBook".equals(ori.getMethodToInvoke().getName())) {
assertEquals("PUT",ori.getHttpMethod());
assertNotNull(ori.getURITemplate());
assertFalse(ori.isSubResourceLocator());
}
else if ("deleteBook".equals(ori.getMethodToInvoke().getName())) {
assertEquals("DELETE",ori.getHttpMethod());
assertNotNull(ori.getURITemplate());
assertFalse(ori.isSubResourceLocator());
}
else {
fail("unexpected OperationResourceInfo" + ori.getMethodToInvoke().getName());
}
}
assertEquals(1,rootCri.getSubResources().size());
ClassResourceInfo subCri=rootCri.getSubResources().iterator().next();
assertNull(subCri.getURITemplate());
assertEquals(org.apache.cxf.jaxrs.resources.Book.class,subCri.getResourceClass());
MethodDispatcher subMd=subCri.getMethodDispatcher();
assertEquals(2,subMd.getOperationResourceInfos().size());
OperationResourceInfo subOri=subMd.getOperationResourceInfos().iterator().next();
assertEquals("GET",subOri.getHttpMethod());
assertNotNull(subOri.getURITemplate());
OperationResourceInfo subOri2=subMd.getOperationResourceInfos().iterator().next();
assertEquals("GET",subOri2.getHttpMethod());
assertNotNull(subOri2.getURITemplate());
}
Class: org.apache.cxf.jaxrs.SelectMethodCandidatesTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testFindFromAbstractGenericClass3() throws Exception {
JAXRSServiceFactoryBean sf=new JAXRSServiceFactoryBean();
sf.setResourceClasses(BookEntity.class);
sf.create();
List resources=((JAXRSServiceImpl)sf.getService()).getClassResourceInfos();
String contentTypes="text/xml";
String acceptContentTypes="text/xml";
Message m=new MessageImpl();
m.put(Message.CONTENT_TYPE,"text/xml");
Exchange ex=new ExchangeImpl();
ex.setInMessage(m);
m.setExchange(ex);
Endpoint e=EasyMock.createMock(Endpoint.class);
e.isEmpty();
EasyMock.expectLastCall().andReturn(true).anyTimes();
e.size();
EasyMock.expectLastCall().andReturn(0).anyTimes();
e.getEndpointInfo();
EasyMock.expectLastCall().andReturn(null).anyTimes();
e.get(ServerProviderFactory.class.getName());
EasyMock.expectLastCall().andReturn(ServerProviderFactory.getInstance()).times(3);
e.get("org.apache.cxf.jaxrs.comparator");
EasyMock.expectLastCall().andReturn(null);
EasyMock.replay(e);
ex.put(Endpoint.class,e);
MetadataMap values=new MetadataMap();
OperationResourceInfo ori=findTargetResourceClass(resources,m,"/books","PUT",values,contentTypes,sortMediaTypes(acceptContentTypes));
assertNotNull(ori);
assertEquals("resourceMethod needs to be selected","putEntity",ori.getMethodToInvoke().getName());
String value="The Book 2 ";
m.setContent(InputStream.class,new ByteArrayInputStream(value.getBytes()));
List params=JAXRSUtils.processParameters(ori,values,m);
assertEquals(1,params.size());
Chapter c=(Chapter)params.get(0);
assertNotNull(c);
assertEquals(2L,c.getId());
assertEquals("The Book",c.getTitle());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testFindFromAbstractGenericImpl4() throws Exception {
JAXRSServiceFactoryBean sf=new JAXRSServiceFactoryBean();
sf.setResourceClasses(GenericEntityImpl4.class);
sf.create();
List resources=((JAXRSServiceImpl)sf.getService()).getClassResourceInfos();
String contentTypes="text/xml";
String acceptContentTypes="text/xml";
Message m=new MessageImpl();
m.put(Message.CONTENT_TYPE,"text/xml");
Exchange ex=new ExchangeImpl();
ex.setInMessage(m);
m.setExchange(ex);
Endpoint e=EasyMock.createMock(Endpoint.class);
e.isEmpty();
EasyMock.expectLastCall().andReturn(true).anyTimes();
e.size();
EasyMock.expectLastCall().andReturn(0).anyTimes();
e.getEndpointInfo();
EasyMock.expectLastCall().andReturn(null).anyTimes();
e.get(ServerProviderFactory.class.getName());
EasyMock.expectLastCall().andReturn(ServerProviderFactory.getInstance()).times(2);
e.get("org.apache.cxf.jaxrs.comparator");
EasyMock.expectLastCall().andReturn(null);
EasyMock.replay(e);
ex.put(Endpoint.class,e);
MetadataMap values=new MetadataMap();
OperationResourceInfo ori=findTargetResourceClass(resources,m,"/books","POST",values,contentTypes,sortMediaTypes(acceptContentTypes));
assertNotNull(ori);
assertEquals("resourceMethod needs to be selected","postEntity",ori.getMethodToInvoke().getName());
String value="The Book 2 ";
m.setContent(InputStream.class,new ByteArrayInputStream(value.getBytes()));
List params=JAXRSUtils.processParameters(ori,values,m);
assertEquals(1,params.size());
List> books=(List>)params.get(0);
assertEquals(1,books.size());
Book book=(Book)books.get(0);
assertNotNull(book);
assertEquals(2L,book.getId());
assertEquals("The Book",book.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSelectBar() throws Exception {
JAXRSServiceFactoryBean sf=new JAXRSServiceFactoryBean();
sf.setResourceClasses(org.apache.cxf.jaxrs.resources.TestResource.class);
sf.create();
List resources=((JAXRSServiceImpl)sf.getService()).getClassResourceInfos();
String contentTypes="*/*";
String acceptContentTypes="application/bar,application/foo;q=0.8";
MetadataMap values=new MetadataMap();
OperationResourceInfo ori=findTargetResourceClass(resources,null,"/1/2/3/d/custom","GET",values,contentTypes,sortMediaTypes(acceptContentTypes));
assertNotNull(ori);
assertEquals("readBar",ori.getMethodToInvoke().getName());
acceptContentTypes="application/foo,application/bar;q=0.8";
ori=findTargetResourceClass(resources,null,"/1/2/3/d/custom","GET",values,contentTypes,sortMediaTypes(acceptContentTypes));
assertNotNull(ori);
assertEquals("readFoo",ori.getMethodToInvoke().getName());
acceptContentTypes="application/foo;q=0.5,application/bar";
ori=findTargetResourceClass(resources,null,"/1/2/3/d/custom","GET",values,contentTypes,sortMediaTypes(acceptContentTypes));
assertNotNull(ori);
assertEquals("readBar",ori.getMethodToInvoke().getName());
acceptContentTypes="application/foo,application/bar;q=0.5";
ori=findTargetResourceClass(resources,null,"/1/2/3/d/custom","GET",values,contentTypes,sortMediaTypes(acceptContentTypes));
assertNotNull(ori);
assertEquals("readFoo",ori.getMethodToInvoke().getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testFindFromAbstractGenericImpl5() throws Exception {
JAXRSServiceFactoryBean sf=new JAXRSServiceFactoryBean();
sf.setResourceClasses(ConcreteRestController.class);
sf.create();
List resources=((JAXRSServiceImpl)sf.getService()).getClassResourceInfos();
Message m=createMessage();
m.put(Message.CONTENT_TYPE,"text/xml");
MetadataMap values=new MetadataMap();
OperationResourceInfo ori=findTargetResourceClass(resources,m,"/","POST",values,"text/xml",sortMediaTypes("*/*"));
assertNotNull(ori);
assertEquals("resourceMethod needs to be selected","add",ori.getMethodToInvoke().getName());
String value="The Book ";
m.setContent(InputStream.class,new ByteArrayInputStream(value.getBytes()));
List params=JAXRSUtils.processParameters(ori,values,m);
assertEquals(1,params.size());
ConcreteRestResource book=(ConcreteRestResource)params.get(0);
assertNotNull(book);
assertEquals("The Book",book.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testFindTargetResourceClassWithTemplates() throws Exception {
JAXRSServiceFactoryBean sf=new JAXRSServiceFactoryBean();
sf.setResourceClasses(org.apache.cxf.jaxrs.resources.TestResource.class);
sf.create();
List resources=((JAXRSServiceImpl)sf.getService()).getClassResourceInfos();
String contentTypes="*/*";
String acceptContentTypes="application/xml";
MetadataMap values=new MetadataMap();
OperationResourceInfo ori=findTargetResourceClass(resources,createMessage(),"/1/2/3/d","GET",values,contentTypes,Collections.singletonList(MediaType.valueOf(acceptContentTypes)));
assertNotNull(ori);
assertEquals("listMethod needs to be selected","listMethod",ori.getMethodToInvoke().getName());
acceptContentTypes="application/xml,application/json;q=0.8";
ori=findTargetResourceClass(resources,null,"/1/2/3/d/1","GET",values,contentTypes,JAXRSUtils.parseMediaTypes(acceptContentTypes));
assertNotNull(ori);
assertEquals("readMethod needs to be selected","readMethod",ori.getMethodToInvoke().getName());
contentTypes="application/xml";
acceptContentTypes="application/xml";
ori=findTargetResourceClass(resources,null,"/1/2/3/d/1","GET",values,contentTypes,Collections.singletonList(MediaType.valueOf(acceptContentTypes)));
assertNotNull(ori);
assertEquals("readMethod needs to be selected","readMethod",ori.getMethodToInvoke().getName());
contentTypes="application/json";
acceptContentTypes="application/json";
ori=findTargetResourceClass(resources,null,"/1/2/3/d/1/bar/baz/baz","GET",values,contentTypes,Collections.singletonList(MediaType.valueOf(acceptContentTypes)));
assertNotNull(ori);
assertEquals("readMethod2 needs to be selected","readMethod2",ori.getMethodToInvoke().getName());
contentTypes="application/json";
acceptContentTypes="application/json";
ori=findTargetResourceClass(resources,null,"/1/2/3/d/1","GET",values,contentTypes,Collections.singletonList(MediaType.valueOf(acceptContentTypes)));
assertNotNull(ori);
assertEquals("unlimitedPath needs to be selected","unlimitedPath",ori.getMethodToInvoke().getName());
ori=findTargetResourceClass(resources,null,"/1/2/3/d/1/2","GET",values,contentTypes,Collections.singletonList(MediaType.valueOf(acceptContentTypes)));
assertNotNull(ori);
assertEquals("limitedPath needs to be selected","limitedPath",ori.getMethodToInvoke().getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSelectUsingQualityFactors() throws Exception {
JAXRSServiceFactoryBean sf=new JAXRSServiceFactoryBean();
sf.setResourceClasses(org.apache.cxf.jaxrs.resources.TestResource.class);
sf.create();
List resources=((JAXRSServiceImpl)sf.getService()).getClassResourceInfos();
String contentTypes="*/*";
String acceptContentTypes="application/xml;q=0.5,application/json";
MetadataMap values=new MetadataMap();
OperationResourceInfo ori=findTargetResourceClass(resources,createMessage(),"/1/2/3/d/resource1","GET",values,contentTypes,sortMediaTypes(acceptContentTypes));
assertNotNull(ori);
assertEquals("jsonResource needs to be selected","jsonResource",ori.getMethodToInvoke().getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testDefaultMethod() throws Exception {
JAXRSServiceFactoryBean sf=new JAXRSServiceFactoryBean();
sf.setResourceClasses(DefaultMethodResource.class);
sf.create();
List resources=((JAXRSServiceImpl)sf.getService()).getClassResourceInfos();
String contentType="text/xml";
String acceptContentTypes="text/xml";
Message m=new MessageImpl();
m.put(Message.CONTENT_TYPE,contentType);
Exchange ex=new ExchangeImpl();
ex.setInMessage(m);
m.setExchange(ex);
Endpoint e=EasyMock.createMock(Endpoint.class);
e.isEmpty();
EasyMock.expectLastCall().andReturn(true).anyTimes();
e.size();
EasyMock.expectLastCall().andReturn(0).anyTimes();
e.getEndpointInfo();
EasyMock.expectLastCall().andReturn(null).anyTimes();
e.get(ServerProviderFactory.class.getName());
EasyMock.expectLastCall().andReturn(ServerProviderFactory.getInstance()).times(3);
e.get("org.apache.cxf.jaxrs.comparator");
EasyMock.expectLastCall().andReturn(null);
EasyMock.replay(e);
ex.put(Endpoint.class,e);
MetadataMap values=new MetadataMap();
OperationResourceInfo ori=findTargetResourceClass(resources,m,"/service/all","PUT",values,contentType,sortMediaTypes(acceptContentTypes));
assertNotNull(ori);
assertEquals("resourceMethod needs to be selected","all",ori.getMethodToInvoke().getName());
values.clear();
ori=findTargetResourceClass(resources,m,"/service/all","GET",values,contentType,sortMediaTypes(acceptContentTypes));
assertNotNull(ori);
assertEquals("resourceMethod needs to be selected","getAll",ori.getMethodToInvoke().getName());
ori=findTargetResourceClass(resources,m,"/service","GET",values,contentType,sortMediaTypes(acceptContentTypes));
assertNotNull(ori);
assertEquals("resourceMethod needs to be selected","get",ori.getMethodToInvoke().getName());
}
Class: org.apache.cxf.jaxrs.client.JAXRSClientFactoryBeanTest BooleanVerifier InternalCallVerifier
@Test public void testCreateClientWithUserResource() throws Exception {
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
bean.setAddress("http://bar");
UserResource r=new UserResource();
r.setName(BookStore.class.getName());
r.setPath("/");
UserOperation op=new UserOperation();
op.setName("getDescription");
op.setVerb("GET");
r.setOperations(Collections.singletonList(op));
bean.setModelBeans(r);
assertTrue(bean.create() instanceof BookStore);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testAddLoggingToClient() throws Exception {
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
bean.setAddress("http://bar");
bean.setResourceClass(BookStoreSubresourcesOnly.class);
TestFeature testFeature=new TestFeature();
List features=new ArrayList();
features.add(testFeature);
bean.setFeatures(features);
BookStoreSubresourcesOnly store=bean.create(BookStoreSubresourcesOnly.class,1,2,3);
assertTrue("TestFeature wasn't initialized",testFeature.isInitialized());
BookStoreSubresourcesOnly store2=store.getItself3("id4");
assertEquals("http://bar/bookstore/1/2/3/id4/sub3",WebClient.client(store2).getCurrentURI().toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testTemplateInRootReplaceEmpty() throws Exception {
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
bean.setAddress("http://bar");
bean.setResourceClass(BookStoreSubresourcesOnly.class);
BookStoreSubresourcesOnly store=bean.create(BookStoreSubresourcesOnly.class);
BookStoreSubresourcesOnly store2=store.getItself4("4","11","22","33");
assertEquals("http://bar/bookstore/11/22/33/sub2/4",WebClient.client(store2).getCurrentURI().toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testTemplateInRootAppend() throws Exception {
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
bean.setAddress("http://bar");
bean.setResourceClass(BookStoreSubresourcesOnly.class);
BookStoreSubresourcesOnly store=bean.create(BookStoreSubresourcesOnly.class,1,2,3);
BookStoreSubresourcesOnly store2=store.getItself3("id4");
assertEquals("http://bar/bookstore/1/2/3/id4/sub3",WebClient.client(store2).getCurrentURI().toString());
}
InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testCreateClientCustomLoader() throws Exception {
ProxyClassLoader loader=new ProxyClassLoader(BookStore.class.getClassLoader());
loader.addLoader(BookStore.class.getClassLoader());
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
bean.setAddress("http://bar");
bean.setResourceClass(BookStore.class);
bean.setClassLoader(loader);
BookStore client=(BookStore)bean.createWithValues(BookStore.class);
assertNotNull(client);
assertSame(client.getClass().getClassLoader(),loader);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testGetConduit() throws Exception {
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
bean.setAddress("http://bar");
bean.setResourceClass(BookStore.class);
BookStore store=bean.create(BookStore.class);
Conduit conduit=WebClient.getConfig(store).getConduit();
assertTrue(conduit instanceof HTTPConduit);
}
InternalCallVerifier EqualityVerifier
@Test public void testTemplateInRootPathInherit() throws Exception {
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
bean.setAddress("http://bar");
bean.setResourceClass(BookStoreSubresourcesOnly.class);
BookStoreSubresourcesOnly store=bean.create(BookStoreSubresourcesOnly.class,1,2,3);
BookStoreSubresourcesOnly store2=store.getItself();
assertEquals("http://bar/bookstore/1/2/3/sub1",WebClient.client(store2).getCurrentURI().toString());
}
BooleanVerifier InternalCallVerifier
@Test public void testCreateClient() throws Exception {
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
bean.setAddress("http://bar");
bean.setResourceClass(BookStore.class);
assertTrue(bean.create() instanceof BookStore);
}
BooleanVerifier InternalCallVerifier
@Test public void testCreateClientWithTwoUserResources() throws Exception {
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
bean.setAddress("http://bar");
UserResource r1=new UserResource();
r1.setName(BookStore.class.getName());
r1.setPath("/store");
UserOperation op=new UserOperation();
op.setName("getDescription");
op.setVerb("GET");
r1.setOperations(Collections.singletonList(op));
UserResource r2=new UserResource();
r2.setName(Book.class.getName());
r2.setPath("/book");
UserOperation op2=new UserOperation();
op2.setName("getName");
op2.setVerb("GET");
r2.setOperations(Collections.singletonList(op2));
bean.setModelBeans(r1,r2);
bean.setServiceClass(Book.class);
assertTrue(bean.create() instanceof Book);
}
InternalCallVerifier NullVerifier
@Test public void testComplexProxy() throws Exception {
IProductResource productResource=JAXRSClientFactory.create("http://localhost:9000",IProductResource.class);
assertNotNull(productResource);
IPartsResource parts=productResource.getParts();
assertNotNull(parts);
IProductResource productResourceElement=parts.elementAt("1");
assertNotNull(productResourceElement);
}
InternalCallVerifier EqualityVerifier
@Test public void testTemplateInRootReplace() throws Exception {
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
bean.setAddress("http://bar");
bean.setResourceClass(BookStoreSubresourcesOnly.class);
BookStoreSubresourcesOnly store=bean.create(BookStoreSubresourcesOnly.class,1,2,3);
BookStoreSubresourcesOnly store2=store.getItself2("4","11","33");
assertEquals("http://bar/bookstore/11/2/33/sub2/4",WebClient.client(store2).getCurrentURI().toString());
}
Class: org.apache.cxf.jaxrs.client.WebClientTest InternalCallVerifier EqualityVerifier
@Test public void testBaseCurrentPathAfterChange(){
WebClient wc=WebClient.create(URI.create("http://foo"));
wc.path("bar").path("baz").matrix("m1","m1value").query("q1","q1value");
assertEquals(URI.create("http://foo"),wc.getBaseURI());
assertEquals(URI.create("http://foo/bar/baz;m1=m1value?q1=q1value"),wc.getCurrentURI());
}
InternalCallVerifier EqualityVerifier
@Test public void testPathWithTemplates(){
WebClient wc=WebClient.create(URI.create("http://foo"));
assertEquals(URI.create("http://foo"),wc.getBaseURI());
assertEquals(URI.create("http://foo"),wc.getCurrentURI());
wc.path("{bar}/{foo}",1,2);
assertEquals(URI.create("http://foo"),wc.getBaseURI());
assertEquals(URI.create("http://foo/1/2"),wc.getCurrentURI());
}
InternalCallVerifier EqualityVerifier
@Test public void testNewBaseCurrentWebSocketPath(){
WebClient wc=WebClient.create("ws://foo");
assertEquals(URI.create("ws://foo"),wc.getBaseURI());
assertEquals(URI.create("ws://foo"),wc.getCurrentURI());
wc.to("ws://bar",false);
assertEquals(URI.create("ws://bar"),wc.getBaseURI());
assertEquals(URI.create("ws://bar"),wc.getCurrentURI());
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testHeaders(){
WebClient wc=WebClient.create(URI.create("http://foo"));
wc.header("h1","h1value").header("h2","h2value");
assertEquals(1,wc.getHeaders().get("h1").size());
assertEquals("h1value",wc.getHeaders().getFirst("h1"));
assertEquals(1,wc.getHeaders().get("h2").size());
assertEquals("h2value",wc.getHeaders().getFirst("h2"));
wc.getHeaders().clear();
assertEquals(1,wc.getHeaders().get("h1").size());
assertEquals("h1value",wc.getHeaders().getFirst("h1"));
assertEquals(1,wc.getHeaders().get("h2").size());
assertEquals("h2value",wc.getHeaders().getFirst("h2"));
wc.reset();
assertTrue(wc.getHeaders().isEmpty());
}
InternalCallVerifier EqualityVerifier
@Test public void testBack(){
WebClient wc=WebClient.create(URI.create("http://foo"));
wc.path("bar").path("baz");
assertEquals(URI.create("http://foo"),wc.getBaseURI());
assertEquals(URI.create("http://foo/bar/baz"),wc.getCurrentURI());
wc.back(false);
assertEquals(URI.create("http://foo/bar"),wc.getCurrentURI());
wc.back(false);
assertEquals(URI.create("http://foo"),wc.getCurrentURI());
wc.back(false);
assertEquals(URI.create("http://foo"),wc.getCurrentURI());
}
InternalCallVerifier EqualityVerifier
@Test public void testReplacePathAll(){
WebClient wc=WebClient.create(URI.create("http://foo"));
wc.path("bar").path("baz");
assertEquals(URI.create("http://foo"),wc.getBaseURI());
assertEquals(URI.create("http://foo/bar/baz"),wc.getCurrentURI());
wc.replacePath("/new");
assertEquals(URI.create("http://foo/new"),wc.getCurrentURI());
}
InternalCallVerifier EqualityVerifier
@Test public void testEmptyQuery(){
WebClient wc=WebClient.create("http://foo");
wc.query("_wadl");
assertEquals("http://foo?_wadl",wc.getCurrentURI().toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testForward(){
WebClient wc=WebClient.create("http://foo");
wc.to("http://foo/bar",true);
assertEquals(URI.create("http://foo"),wc.getBaseURI());
assertEquals(URI.create("http://foo/bar"),wc.getCurrentURI());
}
InternalCallVerifier EqualityVerifier
@Test public void testBaseCurrentWebSocketPath(){
WebClient wc=WebClient.create("ws://foo");
assertEquals(URI.create("ws://foo"),wc.getBaseURI());
assertEquals(URI.create("ws://foo"),wc.getCurrentURI());
wc.path("a");
assertEquals(URI.create("ws://foo"),wc.getBaseURI());
assertEquals(URI.create("ws://foo/a"),wc.getCurrentURI());
}
InternalCallVerifier EqualityVerifier
@Test public void testReplacePathLastSegment(){
WebClient wc=WebClient.create(URI.create("http://foo"));
wc.path("bar").path("baz");
assertEquals(URI.create("http://foo"),wc.getBaseURI());
assertEquals(URI.create("http://foo/bar/baz"),wc.getCurrentURI());
wc.replacePath("new");
assertEquals(URI.create("http://foo/bar/new"),wc.getCurrentURI());
}
InternalCallVerifier EqualityVerifier
@Test public void testFragment(){
WebClient wc=WebClient.create(URI.create("http://foo"));
wc.path("bar").path("baz").query("foo","bar").fragment("1");
assertEquals(URI.create("http://foo"),wc.getBaseURI());
assertEquals(URI.create("http://foo/bar/baz?foo=bar#1"),wc.getCurrentURI());
}
InternalCallVerifier EqualityVerifier
@Test public void testResetQueryAndBack(){
WebClient wc=WebClient.create(URI.create("http://foo"));
wc.path("bar").path("baz").query("foo","bar");
assertEquals(URI.create("http://foo"),wc.getBaseURI());
assertEquals(URI.create("http://foo/bar/baz?foo=bar"),wc.getCurrentURI());
wc.resetQuery().back(false);
assertEquals(URI.create("http://foo/bar"),wc.getCurrentURI());
}
InternalCallVerifier EqualityVerifier
@Test public void testReplaceQuery(){
WebClient wc=WebClient.create(URI.create("http://foo"));
wc.path("bar").path("baz").query("foo","bar");
assertEquals(URI.create("http://foo"),wc.getBaseURI());
assertEquals(URI.create("http://foo/bar/baz?foo=bar"),wc.getCurrentURI());
wc.replaceQuery("foo1=bar1");
assertEquals(URI.create("http://foo/bar/baz?foo1=bar1"),wc.getCurrentURI());
}
InternalCallVerifier EqualityVerifier
@Test public void testRemoveHeader(){
WebClient wc=WebClient.create("http://foo").header("a","b");
assertEquals(1,wc.getHeaders().size());
assertEquals("b",wc.getHeaders().getFirst("a"));
wc.replaceHeader("a",null);
assertEquals(0,wc.getHeaders().size());
}
InternalCallVerifier EqualityVerifier
@Test public void testWebClientParamConverter(){
WebClient wc=WebClient.create("http://foo",Collections.singletonList(new ParamConverterProviderImpl()));
wc.path(new ComplexObject());
wc.query("param",new ComplexObject(),new ComplexObject());
assertEquals("http://foo/complex?param=complex¶m=complex",wc.getCurrentURI().toString());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testBaseCurrentPathAfterCopy(){
WebClient wc=WebClient.create(URI.create("http://foo"));
wc.path("bar").path("baz").matrix("m1","m1value").query("q1","q1value");
WebClient wc1=WebClient.fromClient(wc);
assertEquals(URI.create("http://foo/bar/baz;m1=m1value?q1=q1value"),wc1.getBaseURI());
assertEquals(URI.create("http://foo/bar/baz;m1=m1value?q1=q1value"),wc1.getCurrentURI());
}
InternalCallVerifier EqualityVerifier
@Test public void testReplaceHeader(){
WebClient wc=WebClient.create("http://foo").header("a","b");
assertEquals(1,wc.getHeaders().size());
assertEquals("b",wc.getHeaders().getFirst("a"));
wc.replaceHeader("a","c");
assertEquals(1,wc.getHeaders().size());
assertEquals("c",wc.getHeaders().getFirst("a"));
}
InternalCallVerifier EqualityVerifier
@Test public void testNewBaseCurrentPath(){
WebClient wc=WebClient.create("http://foo");
assertEquals(URI.create("http://foo"),wc.getBaseURI());
assertEquals(URI.create("http://foo"),wc.getCurrentURI());
wc.to("http://bar",false);
assertEquals(URI.create("http://bar"),wc.getBaseURI());
assertEquals(URI.create("http://bar"),wc.getCurrentURI());
}
InternalCallVerifier EqualityVerifier
@Test public void testBackFast(){
WebClient wc=WebClient.create(URI.create("http://foo"));
wc.path("bar").path("baz").matrix("m1","m1value");
assertEquals(URI.create("http://foo"),wc.getBaseURI());
assertEquals(URI.create("http://foo/bar/baz;m1=m1value"),wc.getCurrentURI());
wc.back(true);
assertEquals(URI.create("http://foo"),wc.getCurrentURI());
}
InternalCallVerifier EqualityVerifier
@Test public void testCompositePath(){
WebClient wc=WebClient.create("http://foo");
wc.path("/bar/baz/");
assertEquals(URI.create("http://foo"),wc.getBaseURI());
assertEquals(URI.create("http://foo/bar/baz/"),wc.getCurrentURI());
}
InternalCallVerifier EqualityVerifier
@Test public void testReplaceQueryParam(){
WebClient wc=WebClient.create(URI.create("http://foo"));
wc.path("bar").path("baz").query("foo","bar").query("foo1","bar1");
assertEquals(URI.create("http://foo"),wc.getBaseURI());
assertEquals(URI.create("http://foo/bar/baz?foo=bar&foo1=bar1"),wc.getCurrentURI());
wc.replaceQueryParam("foo1","baz");
assertEquals(URI.create("http://foo/bar/baz?foo=bar&foo1=baz"),wc.getCurrentURI());
}
Class: org.apache.cxf.jaxrs.client.cache.ClientCacheTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetTimeStringAsInputStreamAndString() throws Exception {
CacheControlFeature feature=new CacheControlFeature();
try {
feature.setCacheResponseInputStream(true);
final WebTarget base=ClientBuilder.newBuilder().register(feature).build().target(ADDRESS);
final Invocation.Builder cached=base.request("text/plain").header(HttpHeaders.CACHE_CONTROL,"public");
final Response r=cached.get();
assertEquals(Response.Status.OK.getStatusCode(),r.getStatus());
InputStream is=r.readEntity(InputStream.class);
final String r1=IOUtils.readStringFromStream(is);
waitABit();
final String r2=cached.get().readEntity(String.class);
assertEquals(r1,r2);
}
finally {
feature.close();
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetTimeStringAsInputStream() throws Exception {
CacheControlFeature feature=new CacheControlFeature();
try {
final WebTarget base=ClientBuilder.newBuilder().register(feature).build().target(ADDRESS);
final Invocation.Builder cached=base.request("text/plain").header(HttpHeaders.CACHE_CONTROL,"public");
final Response r=cached.get();
assertEquals(Response.Status.OK.getStatusCode(),r.getStatus());
InputStream is=r.readEntity(InputStream.class);
final String r1=IOUtils.readStringFromStream(is);
waitABit();
is=cached.get().readEntity(InputStream.class);
final String r2=IOUtils.readStringFromStream(is);
assertEquals(r1,r2);
}
finally {
feature.close();
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetTimeString(){
CacheControlFeature feature=new CacheControlFeature();
try {
final WebTarget base=ClientBuilder.newBuilder().register(feature).build().target(ADDRESS);
final Invocation.Builder cached=base.request("text/plain").header(HttpHeaders.CACHE_CONTROL,"public");
final Response r=cached.get();
assertEquals(Response.Status.OK.getStatusCode(),r.getStatus());
final String r1=r.readEntity(String.class);
waitABit();
assertEquals(r1,cached.get().readEntity(String.class));
}
finally {
feature.close();
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetJaxbBookCache(){
CacheControlFeature feature=new CacheControlFeature();
try {
final WebTarget base=ClientBuilder.newBuilder().register(feature).build().target(ADDRESS);
final Invocation.Builder cached=setAsLocal(base.request("application/xml")).header(HttpHeaders.CACHE_CONTROL,"public");
final Response r=cached.get();
assertEquals(Response.Status.OK.getStatusCode(),r.getStatus());
final Book b1=r.readEntity(Book.class);
assertEquals("JCache",b1.getName());
assertNotNull(b1.getId());
waitABit();
assertEquals(b1,cached.get().readEntity(Book.class));
}
finally {
feature.close();
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetTimeStringAsStringAndInputStream() throws Exception {
CacheControlFeature feature=new CacheControlFeature();
try {
feature.setCacheResponseInputStream(true);
final WebTarget base=ClientBuilder.newBuilder().register(feature).build().target(ADDRESS);
final Invocation.Builder cached=base.request("text/plain").header(HttpHeaders.CACHE_CONTROL,"public");
final Response r=cached.get();
assertEquals(Response.Status.OK.getStatusCode(),r.getStatus());
final String r1=r.readEntity(String.class);
waitABit();
InputStream is=cached.get().readEntity(InputStream.class);
final String r2=IOUtils.readStringFromStream(is);
assertEquals(r1,r2);
}
finally {
feature.close();
}
}
Class: org.apache.cxf.jaxrs.client.spring.JAXRSClientFactoryBeanTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testClients() throws Exception {
ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext(new String[]{"/org/apache/cxf/jaxrs/client/spring/clients.xml"});
Object bean=ctx.getBean("client1.proxyFactory");
assertNotNull(bean);
bean=ctx.getBean("setHeaderClient.proxyFactory");
assertNotNull(bean);
JAXRSClientFactoryBean cfb=(JAXRSClientFactoryBean)bean;
assertNotNull(cfb.getHeaders());
assertEquals("Get a wrong map size",cfb.getHeaders().size(),1);
assertEquals("Get a wrong username",cfb.getUsername(),"username");
assertEquals("Get a wrong password",cfb.getPassword(),"password");
QName serviceQName=new QName("http://books.com","BookService");
assertEquals(serviceQName,cfb.getServiceName());
assertEquals(serviceQName,cfb.getServiceFactory().getServiceName());
bean=ctx.getBean("ModelClient.proxyFactory");
assertNotNull(bean);
cfb=(JAXRSClientFactoryBean)bean;
assertNotNull(cfb.getHeaders());
assertEquals("Get a wrong map size",cfb.getHeaders().size(),1);
assertEquals("Get a wrong username",cfb.getUsername(),"username");
assertEquals("Get a wrong password",cfb.getPassword(),"password");
ctx.close();
}
Class: org.apache.cxf.jaxrs.ext.MessageContextImplTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetProperty(){
Message m=new MessageImpl();
m.put("a","b");
MessageContext mc=new MessageContextImpl(m);
assertEquals("b",mc.get("a"));
assertNull(mc.get("b"));
}
InternalCallVerifier IdentityVerifier
@Test public void testHttpResponse(){
Message m=new MessageImpl();
MessageContext mc=new MessageContextImpl(m);
HttpServletResponse request=EasyMock.createMock(HttpServletResponse.class);
m.put(AbstractHTTPDestination.HTTP_RESPONSE,request);
HttpServletResponseFilter filter=(HttpServletResponseFilter)mc.getHttpServletResponse();
assertSame(request.getClass(),filter.getResponse().getClass());
filter=(HttpServletResponseFilter)mc.getContext(HttpServletResponse.class);
assertSame(request.getClass(),filter.getResponse().getClass());
}
InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@SuppressWarnings("unchecked") @Test public void testContextResolver(){
ContextResolver resolver=new CustomContextResolver();
ProviderFactory factory=ServerProviderFactory.getInstance();
factory.registerUserProvider(resolver);
Message m=new MessageImpl();
Exchange ex=new ExchangeImpl();
m.setExchange(ex);
ex.setInMessage(m);
Endpoint e=EasyMock.createMock(Endpoint.class);
e.get(ServerProviderFactory.class.getName());
EasyMock.expectLastCall().andReturn(factory);
EasyMock.replay(e);
ex.put(Endpoint.class,e);
MessageContext mc=new MessageContextImpl(m);
ContextResolver resolver2=mc.getResolver(ContextResolver.class,JAXBContext.class);
assertNotNull(resolver2);
assertSame(resolver2,resolver);
}
InternalCallVerifier IdentityVerifier
@Test public void testGetRequest(){
MessageContext mc=new MessageContextImpl(new MessageImpl());
assertSame(RequestImpl.class,mc.getRequest().getClass());
assertSame(RequestImpl.class,mc.getContext(Request.class).getClass());
}
InternalCallVerifier IdentityVerifier
@Test public void testHttpRequest(){
Message m=new MessageImpl();
MessageContext mc=new MessageContextImpl(m);
HttpServletRequest request=EasyMock.createMock(HttpServletRequest.class);
m.put(AbstractHTTPDestination.HTTP_REQUEST,request);
assertSame(request.getClass(),((HttpServletRequestFilter)mc.getHttpServletRequest()).getRequest().getClass());
assertSame(request.getClass(),((HttpServletRequestFilter)mc.getContext(HttpServletRequest.class)).getRequest().getClass());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetPropertyFromOtherMessage(){
Message m1=new MessageImpl();
Message m2=new MessageImpl();
m2.put("a","b");
Exchange ex=new ExchangeImpl();
ex.setInMessage(m1);
ex.setOutMessage(m2);
MessageContext mc=new MessageContextImpl(m1);
assertEquals("b",mc.get("a"));
assertNull(mc.get("b"));
}
InternalCallVerifier IdentityVerifier
@Test public void testGetUriInfo(){
MessageContext mc=new MessageContextImpl(new MessageImpl());
assertSame(UriInfoImpl.class,mc.getUriInfo().getClass());
assertSame(UriInfoImpl.class,mc.getContext(UriInfo.class).getClass());
}
InternalCallVerifier IdentityVerifier
@Test public void testProviders(){
MessageContext mc=new MessageContextImpl(new MessageImpl());
assertSame(ProvidersImpl.class,mc.getProviders().getClass());
assertSame(ProvidersImpl.class,mc.getContext(Providers.class).getClass());
}
InternalCallVerifier IdentityVerifier
@Test public void testGetHttpHeaders(){
MessageContext mc=new MessageContextImpl(new MessageImpl());
assertSame(HttpHeadersImpl.class,mc.getHttpHeaders().getClass());
assertSame(HttpHeadersImpl.class,mc.getContext(HttpHeaders.class).getClass());
}
InternalCallVerifier IdentityVerifier
@Test public void testGetSecurityContext(){
MessageContext mc=new MessageContextImpl(new MessageImpl());
assertSame(SecurityContextImpl.class,mc.getSecurityContext().getClass());
assertSame(SecurityContextImpl.class,mc.getContext(SecurityContext.class).getClass());
}
InternalCallVerifier IdentityVerifier
@Test public void testServletConfig(){
Message m=new MessageImpl();
MessageContext mc=new MessageContextImpl(m);
ServletConfig request=EasyMock.createMock(ServletConfig.class);
m.put(AbstractHTTPDestination.HTTP_CONFIG,request);
assertSame(request.getClass(),mc.getServletConfig().getClass());
assertSame(request.getClass(),mc.getContext(ServletConfig.class).getClass());
}
InternalCallVerifier IdentityVerifier
@Test public void testServletContext(){
Message m=new MessageImpl();
MessageContext mc=new MessageContextImpl(m);
ServletContext request=EasyMock.createMock(ServletContext.class);
m.put(AbstractHTTPDestination.HTTP_CONTEXT,request);
assertSame(request.getClass(),mc.getServletContext().getClass());
assertSame(request.getClass(),mc.getContext(ServletContext.class).getClass());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetPropertyFromExchange(){
Message m=new MessageImpl();
Exchange ex=new ExchangeImpl();
ex.put("a","b");
ex.setInMessage(m);
MessageContext mc=new MessageContextImpl(m);
assertEquals("b",mc.get("a"));
assertNull(mc.get("b"));
}
Class: org.apache.cxf.jaxrs.ext.multipart.ContentDispositionTest InternalCallVerifier EqualityVerifier
@Test public void testContentDispositionWithQuotes(){
ContentDisposition cd=new ContentDisposition(" attachment ; bar=\"foo.txt\" ; baz = baz1");
assertEquals("attachment",cd.getType());
assertEquals("foo.txt",cd.getParameter("bar"));
assertEquals("baz1",cd.getParameter("baz"));
}
InternalCallVerifier EqualityVerifier
@Test public void testContentDispositionWithQuotesAndSemicolon(){
ContentDisposition cd=new ContentDisposition(" attachment ; bar=\"foo;txt\" ; baz = baz1");
assertEquals("attachment",cd.getType());
assertEquals("foo;txt",cd.getParameter("bar"));
assertEquals("baz1",cd.getParameter("baz"));
}
InternalCallVerifier EqualityVerifier
@Test public void testContentDisposition(){
ContentDisposition cd=new ContentDisposition(" attachment ; bar=foo ; baz = baz1");
assertEquals("attachment",cd.getType());
assertEquals("foo",cd.getParameter("bar"));
assertEquals("baz1",cd.getParameter("baz"));
}
Class: org.apache.cxf.jaxrs.ext.multipart.MultipartBodyTest InternalCallVerifier EqualityVerifier
@Test public void testGetAttachments(){
List atts=new ArrayList();
atts.add(createAttachment("p1"));
atts.add(createAttachment("p2"));
MultipartBody b=new MultipartBody(atts);
assertEquals(atts,b.getAllAttachments());
assertEquals(atts.get(0),b.getRootAttachment());
assertEquals(atts.get(1),b.getChildAttachments().get(0));
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetAttachmentsById(){
List atts=new ArrayList();
atts.add(createAttachment("p1"));
atts.add(createAttachment("p2"));
MultipartBody b=new MultipartBody(atts);
assertEquals(atts.get(0),b.getAttachment("p1"));
assertEquals(atts.get(1),b.getAttachment("p2"));
assertNull(b.getAttachment("p3"));
}
Class: org.apache.cxf.jaxrs.ext.search.BeanspectorTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testSimpleBean() throws SearchParseException {
Beanspector bean=new Beanspector(new SimpleBean());
Set getters=bean.getGettersNames();
assertEquals(3,getters.size());
assertTrue(getters.contains("class"));
assertTrue(getters.contains("a"));
assertTrue(getters.contains("promised"));
Set setters=bean.getSettersNames();
assertEquals(1,setters.size());
assertTrue(getters.contains("a"));
}
Class: org.apache.cxf.jaxrs.ext.search.SearchContextImplCustomParserTest BooleanVerifier InternalCallVerifier
@Test public void testQuery(){
Message m=new MessageImpl();
m.put(SearchContextImpl.CUSTOM_SEARCH_QUERY_PARAM_NAME,"$customfilter");
m.put(SearchContextImpl.CUSTOM_SEARCH_PARSER_PROPERTY,new CustomParser());
m.put(Message.QUERY_STRING,"$customfilter=color is red");
SearchCondition sc=new SearchContextImpl(m).getCondition(Color.class);
assertTrue(sc.isMet(new Color("red")));
assertFalse(sc.isMet(new Color("blue")));
}
Class: org.apache.cxf.jaxrs.ext.search.SearchContextImplTest InternalCallVerifier EqualityVerifier
@Test public void testPlainQuery5(){
Message m=new MessageImpl();
m.put("search.use.plain.queries",true);
m.put(Message.QUERY_STRING,"aFrom=1&aTill=3");
String exp=new SearchContextImpl(m).getSearchExpression();
assertEquals("(a=ge=1;a=le=3)",exp);
}
InternalCallVerifier NullVerifier
@Test public void testWrongQueryNoException(){
Message m=new MessageImpl();
m.put("search.block.search.exception",true);
m.put(Message.QUERY_STRING,"_s=ab");
assertNull(new SearchContextImpl(m).getCondition(Book.class));
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSingleEquals(){
Message m=new MessageImpl();
m.put(Message.QUERY_STRING,"_s=name=CXF");
m.put("fiql.support.single.equals.operator","true");
SearchContext context=new SearchContextImpl(m);
SearchCondition sc=context.getCondition(SearchBean.class);
assertNotNull(sc);
PrimitiveStatement ps=sc.getStatement();
assertNotNull(ps);
assertEquals("name",ps.getProperty());
assertEquals("CXF",ps.getValue());
assertEquals(ConditionType.EQUALS,ps.getCondition());
assertEquals(String.class,ps.getValueType());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testPrimitiveStatementSearchBean(){
Message m=new MessageImpl();
m.put(Message.QUERY_STRING,"_s=name==CXF");
SearchContext context=new SearchContextImpl(m);
SearchCondition sc=context.getCondition(SearchBean.class);
assertNotNull(sc);
PrimitiveStatement ps=sc.getStatement();
assertNotNull(ps);
assertEquals("name",ps.getProperty());
assertEquals("CXF",ps.getValue());
assertEquals(ConditionType.EQUALS,ps.getCondition());
assertEquals(String.class,ps.getValueType());
}
InternalCallVerifier EqualityVerifier
@Test public void testPlainQuery2(){
Message m=new MessageImpl();
m.put("search.use.plain.queries",true);
m.put(Message.QUERY_STRING,"a=b&a=b1");
String exp=new SearchContextImpl(m).getSearchExpression();
assertEquals("(a==b,a==b1)",exp);
}
BooleanVerifier InternalCallVerifier
@Test public void testIsMetCompositeObject() throws Exception {
SearchCondition filter=new FiqlParser(TheBook.class,null,Collections.singletonMap("address","address.street")).parse("address==Street1");
TheBook b=new TheBook();
b.setAddress(new TheOwnerAddress("Street1"));
assertTrue(filter.isMet(b));
b.setAddress(new TheOwnerAddress("Street2"));
assertFalse(filter.isMet(b));
}
InternalCallVerifier EqualityVerifier
@Test public void testPlainQuery1(){
Message m=new MessageImpl();
m.put("search.use.plain.queries",true);
m.put(Message.QUERY_STRING,"a=b");
String exp=new SearchContextImpl(m).getSearchExpression();
assertEquals("a==b",exp);
}
BooleanVerifier InternalCallVerifier
@Test public void testIsMetCompositeInterface() throws Exception {
SearchCondition filter=new FiqlParser(TheBook.class,null,Collections.singletonMap("address","addressInterface.street")).parse("address==Street1");
TheBook b=new TheBook();
b.setAddress(new TheOwnerAddress("Street1"));
assertTrue(filter.isMet(b));
b.setAddress(new TheOwnerAddress("Street2"));
assertFalse(filter.isMet(b));
}
InternalCallVerifier EqualityVerifier
@Test public void testPlainQuery4(){
Message m=new MessageImpl();
m.put("search.use.plain.queries",true);
m.put(Message.QUERY_STRING,"a=b&a=b2&c=d&f=g");
String exp=new SearchContextImpl(m).getSearchExpression();
assertEquals("((a==b,a==b2);c==d;f==g)",exp);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testPrimitiveStatementSearchBeanComlexName(){
Message m=new MessageImpl();
m.put(Message.QUERY_STRING,"_s=complex.name==CXF");
SearchContext context=new SearchContextImpl(m);
SearchCondition sc=context.getCondition(SearchBean.class);
assertNotNull(sc);
PrimitiveStatement ps=sc.getStatement();
assertNotNull(ps);
assertEquals("complex.name",ps.getProperty());
assertEquals("CXF",ps.getValue());
assertEquals(ConditionType.EQUALS,ps.getCondition());
assertEquals(String.class,ps.getValueType());
}
InternalCallVerifier EqualityVerifier
@Test public void testPlainQuery3(){
Message m=new MessageImpl();
m.put("search.use.plain.queries",true);
m.put(Message.QUERY_STRING,"a=b&c=d");
String exp=new SearchContextImpl(m).getSearchExpression();
assertEquals("(a==b;c==d)",exp);
}
Class: org.apache.cxf.jaxrs.ext.search.SimpleSearchConditionTest BranchVerifier UtilityVerifier InternalCallVerifier
@Test public void testCtorCondSupported(){
for ( ConditionType ct : ConditionType.values()) {
try {
new SimpleSearchCondition(ct,attr);
if (!supported.contains(ct)) {
fail(String.format("Not supported type %s should throw exception",ct.name()));
}
}
catch ( IllegalArgumentException e) {
if (supported.contains(ct)) {
fail(String.format("Supported type %s should not throw exception",ct.name()));
}
}
}
}
BooleanVerifier InternalCallVerifier
@Test public void testIsMetGeqDouble2Vals(){
assertTrue(dc2Geq.isMet(attr2ValsGreater));
assertTrue(dc2Geq.isMet(attr2Vals));
assertFalse(dc2Geq.isMet(attr2ValsLesser));
}
BooleanVerifier InternalCallVerifier
@Test public void testIsMetGtDouble1Val(){
assertTrue(dc1Gt.isMet(attr1ValGreater));
assertFalse(dc1Gt.isMet(attr1Val));
assertFalse(dc1Gt.isMet(attr1ValLesser));
}
BooleanVerifier InternalCallVerifier
@Test public void testIsMetWildcardEnds(){
SimpleSearchCondition ssc=new SimpleSearchCondition(ConditionType.EQUALS,"bar*");
assertTrue(ssc.isMet("bar"));
assertTrue(ssc.isMet("barbaz"));
assertFalse(ssc.isMet("foobar"));
}
BooleanVerifier InternalCallVerifier
@Test public void testIsMetWildcardStarts(){
SimpleSearchCondition ssc=new SimpleSearchCondition(ConditionType.EQUALS,"*bar");
assertTrue(ssc.isMet("bar"));
assertFalse(ssc.isMet("barbaz"));
assertTrue(ssc.isMet("foobar"));
}
BooleanVerifier InternalCallVerifier
@Test public void testIsMetLtDouble2Vals(){
assertFalse(dc2Lt.isMet(attr2ValsGreater));
assertFalse(dc2Lt.isMet(attr2Vals));
assertTrue(dc2Lt.isMet(attr2ValsLesser));
}
BooleanVerifier InternalCallVerifier
@Test public void testIsMetGeq(){
assertTrue(cGeq.isMet(attrGreater));
assertTrue(cGeq.isMet(attr));
assertFalse(cGeq.isMet(attrLesser));
}
BooleanVerifier InternalCallVerifier
@Test public void testIsMetLtDouble1Val(){
assertFalse(dc1Lt.isMet(attr1ValGreater));
assertFalse(dc1Lt.isMet(attr1Val));
assertTrue(dc1Lt.isMet(attr1ValLesser));
}
BranchVerifier UtilityVerifier InternalCallVerifier
@Test public void testCtorMapCondSupported(){
for ( ConditionType ct : ConditionType.values()) {
try {
Map map=new HashMap();
map.put("foo",ct);
new SimpleSearchCondition(map,attr);
if (!supported.contains(ct)) {
fail(String.format("Not supported type %s should throw exception",ct.name()));
}
}
catch ( IllegalArgumentException e) {
if (supported.contains(ct)) {
fail(String.format("Supported type %s should not throw exception",ct.name()));
}
}
}
}
BooleanVerifier InternalCallVerifier
@Test public void testIsMetLeq(){
assertFalse(cLeq.isMet(attrGreater));
assertTrue(cLeq.isMet(attr));
assertTrue(cLeq.isMet(attrLesser));
}
BooleanVerifier InternalCallVerifier
@Test public void testIsMetGt(){
assertTrue(cGt.isMet(attrGreater));
assertFalse(cGt.isMet(attr));
assertFalse(cGt.isMet(attrLesser));
}
BooleanVerifier InternalCallVerifier
@Test public void testIsMetLt(){
assertFalse(cLt.isMet(attrGreater));
assertFalse(cLt.isMet(attr));
assertTrue(cLt.isMet(attrLesser));
}
BooleanVerifier InternalCallVerifier
@Test public void testIsMetGeqDouble1Val(){
assertTrue(dc1Geq.isMet(attr1ValGreater));
assertTrue(dc1Geq.isMet(attr1Val));
assertFalse(dc1Geq.isMet(attr1ValLesser));
}
BooleanVerifier InternalCallVerifier
@Test public void testIsMetEqDouble2Vals(){
assertFalse(dc2Eq.isMet(attr2ValsGreater));
assertTrue(dc2Eq.isMet(attr2Vals));
assertFalse(dc2Eq.isMet(attr2ValsLesser));
}
BooleanVerifier InternalCallVerifier
@Test public void testIsMetEqDouble1Val(){
assertFalse(dc1Eq.isMet(attr1ValGreater));
assertTrue(dc1Eq.isMet(attr1Val));
assertFalse(dc1Eq.isMet(attr1ValLesser));
}
BooleanVerifier InternalCallVerifier
@Test public void testIsMetLeqDouble2Vals(){
assertFalse(dc2Leq.isMet(attr2ValsGreater));
assertTrue(dc2Leq.isMet(attr2Vals));
assertTrue(dc2Leq.isMet(attr2ValsLesser));
}
BooleanVerifier InternalCallVerifier
@Test public void testIsMetWildcardStartsEnds(){
SimpleSearchCondition ssc=new SimpleSearchCondition(ConditionType.EQUALS,"*bar*");
assertTrue(ssc.isMet("bar"));
assertTrue(ssc.isMet("barbaz"));
assertTrue(ssc.isMet("foobar"));
}
BooleanVerifier InternalCallVerifier
@Test public void testIsMetWildcardMultiAsterisk(){
SimpleSearchCondition ssc=new SimpleSearchCondition(ConditionType.EQUALS,"*ba*r*");
assertFalse(ssc.isMet("bar"));
assertTrue(ssc.isMet("ba*r"));
assertTrue(ssc.isMet("fooba*r"));
assertTrue(ssc.isMet("fooba*rbaz"));
assertFalse(ssc.isMet("foobarbaz"));
}
BooleanVerifier InternalCallVerifier
@Test public void testIsMetLeqDouble1Val(){
assertFalse(dc1Leq.isMet(attr1ValGreater));
assertTrue(dc1Leq.isMet(attr1Val));
assertTrue(dc1Leq.isMet(attr1ValLesser));
}
BooleanVerifier InternalCallVerifier
@Test public void testIsMetEq(){
assertTrue(cEq.isMet(attr));
assertFalse(cEq.isMet(attrGreater));
}
BooleanVerifier InternalCallVerifier
@Test public void testIsMetGtDouble2Vals(){
assertTrue(dc2Gt.isMet(attr2ValsGreater));
assertFalse(dc2Gt.isMet(attr2Vals));
assertFalse(dc2Gt.isMet(attr2ValsLesser));
}
Class: org.apache.cxf.jaxrs.ext.search.client.FiqlSearchConditionBuilderTest InternalCallVerifier EqualityVerifier
@Test public void testLessOrEqualToNumberDouble(){
String ret=b.is("foo").lessOrEqualTo(0.0).query();
assertEquals("foo=le=0.0",ret);
}
InternalCallVerifier EqualityVerifier
@Test public void testComplex1(){
String ret=b.is("foo").equalTo(123.4).or().and(b.is("bar").equalTo("asadf*"),b.is("baz").lessThan(20)).query();
assertEquals("foo==123.4,(bar==asadf*;baz=lt=20)",ret);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGreaterOrEqualToDuration() throws DatatypeConfigurationException {
Duration d=DatatypeFactory.newInstance().newDuration(false,0,0,1,12,0,0);
String ret=b.is("foo").notBefore(d).query();
assertEquals("foo=ge=-P0Y0M1DT12H0M0S",ret);
}
InternalCallVerifier EqualityVerifier
@Test public void testEqualToString(){
String ret=b.is("foo").equalTo("literalOrPattern*").query();
assertEquals("foo==literalOrPattern*",ret);
}
InternalCallVerifier EqualityVerifier
@Test public void testLessOrEqualToString(){
String ret=b.is("foo").lexicalNotAfter("abc").query();
assertEquals("foo=le=abc",ret);
}
InternalCallVerifier EqualityVerifier
@Test public void testMultipleOrShortcutWithAnd2(){
String ret=b.is("foo").equalTo(123.4,137.8).or("n").equalTo("n1").and("bar").equalTo("baz").query();
assertEquals("(foo==123.4,foo==137.8,n==n1);bar==baz",ret);
}
InternalCallVerifier EqualityVerifier
@Test public void testLessThanString(){
String ret=b.is("foo").lexicalBefore("abc").query();
assertEquals("foo=lt=abc",ret);
}
InternalCallVerifier EqualityVerifier
@Test public void testEqualToNumberCondition(){
String ret=b.is("foo").comparesTo(ConditionType.LESS_THAN,123.5).query();
assertEquals("foo=lt=123.5",ret);
}
InternalCallVerifier EqualityVerifier
@Test public void testGreaterThanLong(){
String ret=b.is("foo").greaterThan(25).query();
assertEquals("foo=gt=25",ret);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testLessThanDuration() throws DatatypeConfigurationException {
Duration d=DatatypeFactory.newInstance().newDuration(false,0,0,1,12,0,0);
String ret=b.is("foo").before(d).query();
assertEquals("foo=lt=-P0Y0M1DT12H0M0S",ret);
}
InternalCallVerifier EqualityVerifier
@Test public void testGreaterThanNumberDouble(){
String ret=b.is("foo").greaterThan(25.0).query();
assertEquals("foo=gt=25.0",ret);
}
InternalCallVerifier EqualityVerifier
@Test public void testGreaterOrEqualToString(){
String ret=b.is("foo").lexicalNotBefore("abc").query();
assertEquals("foo=ge=abc",ret);
}
InternalCallVerifier EqualityVerifier
@Test public void testNotEqualToString(){
String ret=b.is("foo").notEqualTo("literalOrPattern*").query();
assertEquals("foo!=literalOrPattern*",ret);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testLessOrEqualToDate() throws ParseException {
Date d=parseDate(SearchUtils.DEFAULT_DATE_FORMAT,"2011-03-02");
String ret=b.is("foo").notAfter(d).query();
assertEquals("foo=le=2011-03-02",ret);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testLessThanDate() throws ParseException {
Date d=parseDate(SearchUtils.DEFAULT_DATE_FORMAT,"2011-03-02");
String ret=b.is("foo").before(d).query();
assertEquals("foo=lt=2011-03-02",ret);
}
InternalCallVerifier EqualityVerifier
@Test public void testAndSimpleShortcut(){
String ret=b.is("foo").greaterThan(20).and("bar").equalTo("plonk").query();
assertEquals("foo=gt=20;bar==plonk",ret);
}
InternalCallVerifier EqualityVerifier
@Test public void testLessThanNumber(){
String ret=b.is("foo").lessThan(25.333).query();
assertEquals("foo=lt=25.333",ret);
}
InternalCallVerifier EqualityVerifier
@Test public void testMultipleOrShortcut(){
String ret=b.is("foo").equalTo(123.4,137.8).query();
assertEquals("foo==123.4,foo==137.8",ret);
}
InternalCallVerifier EqualityVerifier
@Test public void testEqualToNumber(){
String ret=b.is("foo").equalTo(123.5).query();
assertEquals("foo==123.5",ret);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGreaterThanDate() throws ParseException {
Date d=parseDate(SearchUtils.DEFAULT_DATE_FORMAT,"2011-03-02");
String ret=b.is("foo").after(d).query();
assertEquals("foo=gt=2011-03-02",ret);
}
InternalCallVerifier EqualityVerifier
@Test public void testAndComplex(){
String ret=b.and(b.is("foo").equalTo("aaa"),b.is("bar").equalTo("bbb")).query();
assertEquals("(foo==aaa;bar==bbb)",ret);
}
InternalCallVerifier EqualityVerifier
@Test public void testOrSimpleShortcut(){
String ret=b.is("foo").greaterThan(20).or("foo").lessThan(10).query();
assertEquals("foo=gt=20,foo=lt=10",ret);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGreaterThanDuration() throws DatatypeConfigurationException {
Duration d=DatatypeFactory.newInstance().newDuration(false,0,0,1,12,0,0);
String ret=b.is("foo").after(d).query();
assertEquals("foo=gt=-P0Y0M1DT12H0M0S",ret);
}
InternalCallVerifier EqualityVerifier
@Test public void testMultipleOrShortcutWithAnd(){
String ret=b.is("foo").equalTo(123.4,137.8).and("bar").equalTo("baz").query();
assertEquals("(foo==123.4,foo==137.8);bar==baz",ret);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testEqualToDateWithCustomFormat() throws ParseException {
Map props=new HashMap();
props.put(SearchUtils.DATE_FORMAT_PROPERTY,"yyyy-MM-dd'T'HH:mm:ss");
props.put(SearchUtils.TIMEZONE_SUPPORT_PROPERTY,"false");
Date d=parseDate("yyyy-MM-dd HH:mm Z","2011-03-01 12:34 +0000");
FiqlSearchConditionBuilder bCustom=new FiqlSearchConditionBuilder(props);
String ret=bCustom.is("foo").equalTo(d).query();
assertEquals("foo==2011-03-01T12:34:00",ret);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testNotEqualToDuration() throws ParseException, DatatypeConfigurationException {
Duration d=DatatypeFactory.newInstance().newDuration(false,0,0,1,12,0,0);
String ret=b.is("foo").notEqualTo(d).query();
assertEquals("foo!=-P0Y0M1DT12H0M0S",ret);
}
InternalCallVerifier EqualityVerifier
@Test public void testAndSimple(){
String ret=b.is("foo").greaterThan(20).and().is("bar").equalTo("plonk").query();
assertEquals("foo=gt=20;bar==plonk",ret);
}
InternalCallVerifier EqualityVerifier
@Test public void testOrComplex(){
String ret=b.or(b.is("foo").equalTo("aaa"),b.is("bar").equalTo("bbb")).query();
assertEquals("(foo==aaa,bar==bbb)",ret);
}
InternalCallVerifier EqualityVerifier
@Test public void testLessOrEqualToNumberLong(){
String ret=b.is("foo").lessOrEqualTo(0).query();
assertEquals("foo=le=0",ret);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testEqualToDuration() throws ParseException, DatatypeConfigurationException {
Duration d=DatatypeFactory.newInstance().newDuration(false,0,0,1,12,0,0);
String ret=b.is("foo").equalTo(d).query();
assertEquals("foo==-P0Y0M1DT12H0M0S",ret);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testLessOrEqualToDuration() throws DatatypeConfigurationException {
Duration d=DatatypeFactory.newInstance().newDuration(false,0,0,1,12,0,0);
String ret=b.is("foo").notAfter(d).query();
assertEquals("foo=le=-P0Y0M1DT12H0M0S",ret);
}
InternalCallVerifier EqualityVerifier
@Test public void testOrAndImplicitWrap(){
String ret=b.is("foo").equalTo(1,2).and("bar").equalTo("baz").query();
assertEquals("(foo==1,foo==2);bar==baz",ret);
}
InternalCallVerifier EqualityVerifier
@Test public void testNotEqualToNumber(){
String ret=b.is("foo").notEqualTo(123.5).query();
assertEquals("foo!=123.5",ret);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGreaterOrEqualToDate() throws ParseException {
Date d=parseDate(SearchUtils.DEFAULT_DATE_FORMAT,"2011-03-02");
String ret=b.is("foo").notBefore(d).query();
assertEquals("foo=ge=2011-03-02",ret);
}
InternalCallVerifier EqualityVerifier
@Test public void testGreaterOrEqualToNumberLong(){
String ret=b.is("foo").greaterOrEqualTo(-5).query();
assertEquals("foo=ge=-5",ret);
}
InternalCallVerifier EqualityVerifier
@Test public void testGreaterThanString(){
String ret=b.is("foo").lexicalAfter("abc").query();
assertEquals("foo=gt=abc",ret);
}
InternalCallVerifier EqualityVerifier
@Test public void testOrSimple(){
String ret=b.is("foo").greaterThan(20).or().is("foo").lessThan(10).query();
assertEquals("foo=gt=20,foo=lt=10",ret);
}
InternalCallVerifier EqualityVerifier
@Test public void testGreaterOrEqualToNumberDouble(){
String ret=b.is("foo").greaterOrEqualTo(-5.0).query();
assertEquals("foo=ge=-5.0",ret);
}
InternalCallVerifier EqualityVerifier
@Test public void testComplex2(){
String ret=b.is("foo").equalTo(123L).or().is("foo").equalTo("null").and().or(b.is("bar").equalTo("asadf*"),b.is("baz").lessThan(20).and().or(b.is("sub1").equalTo(0L),b.is("sub2").equalTo(0L))).query();
assertEquals("foo==123,foo==null;(bar==asadf*,baz=lt=20;(sub1==0,sub2==0))",ret);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testNotEqualToDateDefault() throws ParseException {
Date d=parseDate(SearchUtils.DEFAULT_DATE_FORMAT,"2011-03-01");
String ret=b.is("foo").notEqualTo(d).query();
assertEquals("foo!=2011-03-01",ret);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testEqualToDateDefault() throws ParseException {
Date d=parseDate(SearchUtils.DEFAULT_DATE_FORMAT,"2011-03-01");
String ret=b.is("foo").equalTo(d).query();
assertEquals("foo==2011-03-01",ret);
}
Class: org.apache.cxf.jaxrs.ext.search.fiql.FiqlParserTest BooleanVerifier InternalCallVerifier
@Test public void testParseDateDuration() throws Exception {
SearchCondition filter=parser.parse("time=gt=-PT1M");
Date now=new Date();
Date tenMinutesAgo=new Date();
DatatypeFactory.newInstance().newDuration("-PT10M").addTo(tenMinutesAgo);
assertTrue(filter.isMet(new Condition(null,null,now)));
assertFalse(filter.isMet(new Condition(null,null,tenMinutesAgo)));
}
BooleanVerifier InternalCallVerifier
@Test public void testParseLevel() throws SearchParseException {
SearchCondition filter=parser.parse("level=gt=10");
assertTrue(filter.isMet(new Condition("whatever",15,new Date())));
assertTrue(filter.isMet(new Condition(null,15,null)));
assertFalse(filter.isMet(new Condition("blah",5,new Date())));
assertFalse(filter.isMet(new Condition("foobar",0,null)));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testSQL4() throws SearchParseException {
SearchCondition filter=parser.parse("(name==test,level==18);(name==test1,level!=19)");
String sql=SearchUtils.toSQL(filter,"table");
assertTrue(("SELECT * FROM table WHERE ((name = 'test') OR (level = '18'))" + " AND ((name = 'test1') OR (level <> '19'))").equals(sql) || ("SELECT * FROM table WHERE ((name = 'test1') OR (level <> '19'))" + " AND ((name = 'test') OR (level = '18'))").equals(sql));
}
InternalCallVerifier EqualityVerifier
@Test public void testMultipleLists() throws SearchParseException {
FiqlParser jobParser=new FiqlParser(Job.class,Collections.emptyMap(),Collections.singletonMap("itemName","tasks.items.itemName"));
SearchCondition jobCondition=jobParser.parse("itemName==myitem");
Job job=jobCondition.getCondition();
assertEquals("myitem",job.getTasks().get(0).getItems().get(0).getItemName());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testSQL5() throws SearchParseException {
SearchCondition filter=parser.parse("name==test");
String sql=SearchUtils.toSQL(filter,"table");
assertTrue("SELECT * FROM table WHERE name = 'test'".equals(sql));
}
BooleanVerifier InternalCallVerifier
@Test public void testParseComplex3() throws SearchParseException {
SearchCondition filter=parser.parse("name==foo*;(name!=*bar,level=gt=10)");
assertTrue(filter.isMet(new Condition("fooooo",0,null)));
assertTrue(filter.isMet(new Condition("fooooobar",20,null)));
assertFalse(filter.isMet(new Condition("fooobar",0,null)));
assertFalse(filter.isMet(new Condition("bar",20,null)));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testSQL1() throws SearchParseException {
SearchCondition filter=parser.parse("name==ami*;level=gt=10");
String sql=SearchUtils.toSQL(filter,"table");
assertTrue("SELECT * FROM table WHERE (name LIKE 'ami%') AND (level > '10')".equals(sql) || "SELECT * FROM table WHERE (level > '10') AND (name LIKE 'ami%')".equals(sql));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testSQL3() throws SearchParseException {
SearchCondition filter=parser.parse("name==foo*;(name!=*bar,level=gt=10)");
String sql=SearchUtils.toSQL(filter,"table");
assertTrue(("SELECT * FROM table WHERE (name LIKE 'foo%') AND ((name NOT LIKE '%bar') " + "OR (level > '10'))").equals(sql) || ("SELECT * FROM table WHERE (name LIKE 'foo%') AND " + "((level > '10') OR (name NOT LIKE '%bar'))").equals(sql));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testParseComplex2() throws SearchParseException {
SearchCondition filter=parser.parse("name==ami*,level=gt=10");
assertEquals(ConditionType.OR,filter.getConditionType());
List> conditions=filter.getSearchConditions();
assertEquals(2,conditions.size());
PrimitiveStatement st1=conditions.get(0).getStatement();
PrimitiveStatement st2=conditions.get(1).getStatement();
assertTrue((ConditionType.EQUALS.equals(st1.getCondition()) && ConditionType.GREATER_THAN.equals(st2.getCondition())) || (ConditionType.EQUALS.equals(st2.getCondition()) && ConditionType.GREATER_THAN.equals(st1.getCondition())));
assertTrue(filter.isMet(new Condition("ami",0,new Date())));
assertTrue(filter.isMet(new Condition("foo",20,null)));
assertFalse(filter.isMet(new Condition("foo",0,null)));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testSQL2() throws SearchParseException {
SearchCondition filter=parser.parse("name==ami*,level=gt=10");
String sql=SearchUtils.toSQL(filter,"table");
assertTrue("SELECT * FROM table WHERE (name LIKE 'ami%') OR (level > '10')".equals(sql) || "SELECT * FROM table WHERE (level > '10') OR (name LIKE 'ami%')".equals(sql));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testParseComplex1() throws SearchParseException {
SearchCondition filter=parser.parse("name==ami*;level=gt=10");
assertEquals(ConditionType.AND,filter.getConditionType());
List> conditions=filter.getSearchConditions();
assertEquals(2,conditions.size());
PrimitiveStatement st1=conditions.get(0).getStatement();
PrimitiveStatement st2=conditions.get(1).getStatement();
assertTrue((ConditionType.EQUALS.equals(st1.getCondition()) && ConditionType.GREATER_THAN.equals(st2.getCondition())) || (ConditionType.EQUALS.equals(st2.getCondition()) && ConditionType.GREATER_THAN.equals(st1.getCondition())));
assertTrue(filter.isMet(new Condition("amichalec",12,new Date())));
assertTrue(filter.isMet(new Condition("ami",12,new Date())));
assertFalse(filter.isMet(new Condition("ami",8,null)));
assertFalse(filter.isMet(new Condition("am",20,null)));
}
BooleanVerifier InternalCallVerifier
@Test public void testParseComplex4() throws SearchParseException {
SearchCondition filter=parser.parse("name==foo*;name!=*bar,level=gt=10");
assertTrue(filter.isMet(new Condition("zonk",20,null)));
assertTrue(filter.isMet(new Condition("foobaz",0,null)));
assertTrue(filter.isMet(new Condition("foobar",20,null)));
assertFalse(filter.isMet(new Condition("fooxxxbar",0,null)));
}
BooleanVerifier InternalCallVerifier
@Test public void testParseDateWithDefaultFormat() throws SearchParseException, ParseException {
SearchCondition filter=parser.parse("time=le=2010-03-11T18:00:00.000+00:00");
DateFormat df=new SimpleDateFormat(SearchUtils.DEFAULT_DATE_FORMAT);
assertTrue(filter.isMet(new Condition("whatever",15,df.parse("2010-03-11T18:00:00.000+0000"))));
assertTrue(filter.isMet(new Condition(null,null,df.parse("2010-03-10T22:22:00.000+0000"))));
assertFalse(filter.isMet(new Condition("blah",null,df.parse("2010-03-12T00:00:00.000+0000"))));
assertFalse(filter.isMet(new Condition(null,123,df.parse("2010-03-12T00:00:00.000+0000"))));
}
BooleanVerifier InternalCallVerifier
@Test public void testParseDateWithCustomFormat() throws SearchParseException, ParseException {
Map props=new HashMap();
props.put(SearchUtils.DATE_FORMAT_PROPERTY,"yyyy-MM-dd'T'HH:mm:ss");
props.put(SearchUtils.TIMEZONE_SUPPORT_PROPERTY,"false");
parser=new FiqlParser(Condition.class,props);
SearchCondition filter=parser.parse("time=le=2010-03-11T18:00:00");
DateFormat df=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
assertTrue(filter.isMet(new Condition("whatever",15,df.parse("2010-03-11T18:00:00"))));
assertTrue(filter.isMet(new Condition(null,null,df.parse("2010-03-10T22:22:00"))));
assertFalse(filter.isMet(new Condition("blah",null,df.parse("2010-03-12T00:00:00"))));
assertFalse(filter.isMet(new Condition(null,123,df.parse("2010-03-12T00:00:00"))));
}
Class: org.apache.cxf.jaxrs.ext.search.hbase.HBaseVisitorTest IterativeVerifier InternalCallVerifier EqualityVerifier IgnoredMethod HybridVerifier
@Test @Ignore("Enable as soon as it is understood how to run HBase tests in process") public void testScanWithFilterVisitor() throws Exception {
Scan scan=new Scan();
SearchCondition sc=new FiqlParser(SearchBean.class).parse("name==CXF");
HBaseQueryVisitor visitor=new HBaseQueryVisitor("book");
sc.accept(visitor);
Filter filter=visitor.getQuery();
scan.setFilter(filter);
ResultScanner rs=table.getScanner(scan);
try {
int count=0;
for (Result r=rs.next(); r != null; r=rs.next()) {
assertEquals("row2",new String(r.getRow()));
assertEquals("CXF",new String(r.getValue(BOOK_FAMILY,NAME_QUALIFIER)));
count++;
}
assertEquals(1,count);
}
finally {
rs.close();
}
}
Class: org.apache.cxf.jaxrs.ext.search.jpa.AbstractJPATypedQueryVisitorTest TestInitializer UtilityVerifier BooleanVerifier InternalCallVerifier HybridVerifier
@Before public void setUp() throws Exception {
try {
Class.forName("org.hsqldb.jdbcDriver");
connection=DriverManager.getConnection("jdbc:hsqldb:mem:books-jpa","sa","");
}
catch ( Exception ex) {
ex.printStackTrace();
fail("Exception during HSQL database init.");
}
try {
emFactory=Persistence.createEntityManagerFactory("testUnitHibernate");
em=emFactory.createEntityManager();
em.getTransaction().begin();
Library lib=new Library();
lib.setId(1);
lib.setAddress("town");
em.persist(lib);
assertTrue(em.contains(lib));
BookReview br1=new BookReview();
br1.setId(1);
br1.setReview(Review.BAD);
br1.getAuthors().add("Ted");
em.persist(br1);
Book b1=new Book();
br1.setBook(b1);
b1.getReviews().add(br1);
b1.setId(9);
b1.setBookTitle("num9");
b1.setAddress(new OwnerAddress("Street1"));
OwnerInfo info1=new OwnerInfo();
info1.setName(new Name("Fred"));
info1.setDateOfBirth(parseDate("2000-01-01"));
b1.setOwnerInfo(info1);
b1.setLibrary(lib);
b1.getAuthors().add("John");
em.persist(b1);
BookReview br2=new BookReview();
br2.setId(2);
br2.setReview(Review.GOOD);
br2.getAuthors().add("Ted");
em.persist(br2);
Book b2=new Book();
b2.getReviews().add(br2);
br2.setBook(b2);
b2.setId(10);
b2.setBookTitle("num10");
b2.setAddress(new OwnerAddress("Street2"));
OwnerInfo info2=new OwnerInfo();
info2.setName(new Name("Barry"));
info2.setDateOfBirth(parseDate("2001-01-01"));
b2.setOwnerInfo(info2);
b2.setLibrary(lib);
b2.getAuthors().add("John");
em.persist(b2);
BookReview br3=new BookReview();
br3.setId(3);
br3.setReview(Review.GOOD);
br3.getAuthors().add("Ted");
em.persist(br3);
Book b3=new Book();
b3.getReviews().add(br3);
br3.setBook(b3);
b3.setId(11);
b3.setBookTitle("num11");
b3.setAddress(new OwnerAddress("Street&'3"));
b3.getAuthors().add("Barry");
OwnerInfo info3=new OwnerInfo();
info3.setName(new Name("Bill"));
info3.setDateOfBirth(parseDate("2002-01-01"));
b3.setOwnerInfo(info3);
b3.setLibrary(lib);
em.persist(b3);
lib.getBooks().add(b1);
lib.getBooks().add(b2);
lib.getBooks().add(b3);
em.getTransaction().commit();
}
catch ( Exception ex) {
ex.printStackTrace();
fail("Exception during JPA EntityManager creation.");
}
}
Class: org.apache.cxf.jaxrs.ext.search.jpa.JPATypedQueryVisitorFiqlTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testEqualsAddressQuery2() throws Exception {
List books=queryBooks("street==Street1",null,Collections.singletonMap("street","address.street"));
assertEquals(1,books.size());
Book book=books.get(0);
assertTrue(9 == book.getId());
assertEquals("Street1",book.getAddress().getStreet());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testEqualsAddressQuery3() throws Exception {
Map beanPropertiesMap=new HashMap();
beanPropertiesMap.put("street","address.street");
beanPropertiesMap.put("housenum","address.houseNumber");
List books=queryBooks("street==Street2;housenum=lt=5",null,beanPropertiesMap);
assertEquals(1,books.size());
Book book=books.get(0);
assertTrue(10 == book.getId());
assertEquals("Street2",book.getAddress().getStreet());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testEqualsCriteriaQueryTuple() throws Exception {
List books=criteriaQueryBooksTuple("id==10");
assertEquals(1,books.size());
Tuple tuple=books.get(0);
int tupleId=tuple.get("id",Integer.class);
assertEquals(10,tupleId);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testEqualsAddressQuery() throws Exception {
List books=queryBooks("address==Street1",Collections.singletonMap("address","address.street"));
assertEquals(1,books.size());
Book book=books.get(0);
assertTrue(9 == book.getId());
assertEquals("Street1",book.getAddress().getStreet());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testEqualsOwnerBirthDate() throws Exception {
List books=queryBooks("ownerbdate==2000-01-01",null,Collections.singletonMap("ownerbdate","ownerInfo.dateOfBirth"));
assertEquals(1,books.size());
Book book=books.get(0);
assertEquals("Fred",book.getOwnerInfo().getName().getName());
Date d=parseDate("2000-01-01");
assertEquals("Fred",book.getOwnerInfo().getName().getName());
assertEquals(d,book.getOwnerInfo().getDateOfBirth());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testEqualsCriteriaQueryConstruct() throws Exception {
List books=criteriaQueryBooksConstruct("id==10");
assertEquals(1,books.size());
BookInfo info=books.get(0);
assertEquals(10,info.getId());
assertEquals("num10",info.getTitle());
}
Class: org.apache.cxf.jaxrs.ext.search.jpa.JPATypedQueryVisitorODataTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testEqualsCriteriaQueryConstruct() throws Exception {
List books=criteriaQueryBooksConstruct("id eq 10");
assertEquals(1,books.size());
BookInfo info=books.get(0);
assertEquals(10,info.getId());
assertEquals("num10",info.getTitle());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testEqualsAddressQuery() throws Exception {
List books=queryBooks("address eq 'Street1'",Collections.singletonMap("address","address.street"));
assertEquals(1,books.size());
Book book=books.get(0);
assertTrue(9 == book.getId());
assertEquals("Street1",book.getAddress().getStreet());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testEqualsCriteriaQueryTuple() throws Exception {
List books=criteriaQueryBooksTuple("id eq 10");
assertEquals(1,books.size());
Tuple tuple=books.get(0);
int tupleId=tuple.get("id",Integer.class);
assertEquals(10,tupleId);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testEqualsOwnerBirthDate() throws Exception {
List books=queryBooks("ownerbdate eq '2000-01-01'",null,Collections.singletonMap("ownerbdate","ownerInfo.dateOfBirth"));
assertEquals(1,books.size());
Book book=books.get(0);
assertEquals("Fred",book.getOwnerInfo().getName().getName());
Date d=parseDate("2000-01-01");
assertEquals("Fred",book.getOwnerInfo().getName().getName());
assertEquals(d,book.getOwnerInfo().getDateOfBirth());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testEqualsAddressQuery3() throws Exception {
Map beanPropertiesMap=new HashMap();
beanPropertiesMap.put("street","address.street");
beanPropertiesMap.put("housenum","address.houseNumber");
List books=queryBooks("street eq 'Street2' and housenum lt 5",null,beanPropertiesMap);
assertEquals(1,books.size());
Book book=books.get(0);
assertTrue(10 == book.getId());
assertEquals("Street2",book.getAddress().getStreet());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testEqualsAddressQuery2() throws Exception {
List books=queryBooks("street eq 'Street1'",null,Collections.singletonMap("street","address.street"));
assertEquals(1,books.size());
Book book=books.get(0);
assertTrue(9 == book.getId());
assertEquals("Street1",book.getAddress().getStreet());
}
Class: org.apache.cxf.jaxrs.ext.search.ldap.LdapQueryVisitorTest InternalCallVerifier EqualityVerifier
@Test public void testComplexQuery() throws SearchParseException {
SearchCondition filter=parser.parse("(name==test,level==18);(name==test1,level!=19)");
LdapQueryVisitor visitor=new LdapQueryVisitor();
filter.accept(visitor.visitor());
String ldap=visitor.getQuery();
assertEquals("(&(|(name=test)(level=18))(|(name=test1)(!level=19)))",ldap);
}
InternalCallVerifier EqualityVerifier
@Test public void testSimple() throws SearchParseException {
SearchCondition filter=parser.parse("name!=ami");
LdapQueryVisitor visitor=new LdapQueryVisitor();
filter.accept(visitor.visitor());
String ldap=visitor.getQuery();
assertEquals("(!name=ami)",ldap);
}
InternalCallVerifier EqualityVerifier
@Test public void testAndQuery() throws SearchParseException {
SearchCondition filter=parser.parse("name==ami*;level=gt=10");
LdapQueryVisitor visitor=new LdapQueryVisitor();
filter.accept(visitor.visitor());
String ldap=visitor.getQuery();
assertEquals("(&(name=ami*)(level>=10))",ldap);
}
InternalCallVerifier EqualityVerifier
@Test public void testOrQuery() throws SearchParseException {
SearchCondition filter=parser.parse("name==ami*,level=gt=10");
LdapQueryVisitor visitor=new LdapQueryVisitor();
filter.accept(visitor.visitor());
String ldap=visitor.getQuery();
assertEquals("(|(name=ami*)(level>=10))",ldap);
}
InternalCallVerifier EqualityVerifier
@Test public void testAndOrQuery() throws SearchParseException {
SearchCondition filter=parser.parse("name==foo;(name!=bar,level=le=10)");
LdapQueryVisitor visitor=new LdapQueryVisitor();
filter.accept(visitor.visitor());
String ldap=visitor.getQuery();
assertEquals("(&(name=foo)(|(!name=bar)(level<=10)))",ldap);
}
Class: org.apache.cxf.jaxrs.ext.search.lucene.LuceneQueryVisitorFiqlTest BooleanVerifier InternalCallVerifier NullVerifier ConditionMatcher HybridVerifier
@Test public void testThatMultipleQueriesForTheSameFieldAreThreadSafe() throws InterruptedException, ExecutionException {
final LuceneQueryVisitor visitor=new LuceneQueryVisitor();
final ExecutorService executorService=Executors.newFixedThreadPool(5);
final Collection> futures=new ArrayList>();
for (int i=0; i < 5; ++i) {
final int index=i;
futures.add(executorService.submit(new Runnable(){
@Override public void run(){
final SearchCondition filter=getParser().parse("name==text" + index);
visitor.reset();
visitor.visit(filter);
assertNotNull("Query should not be null",visitor.getQuery());
assertThat(visitor.getQuery().toString(),equalTo("name:text" + index));
}
}
));
}
executorService.shutdown();
assertTrue("All threads should be terminated",executorService.awaitTermination(5,TimeUnit.SECONDS));
for ( final Future> future : futures) {
future.get();
}
}
InternalCallVerifier ConditionMatcher
@Test public void testThatMultipleQueriesForTheSameFieldAreHandledProperly(){
final SearchCondition filter1=getParser().parse("name==text");
final SearchCondition filter2=getParser().parse("name==word");
final LuceneQueryVisitor visitor=new LuceneQueryVisitor();
visitor.visit(filter1);
assertThat(visitor.getQuery().toString(),equalTo("name:text"));
visitor.reset();
visitor.visit(filter2);
assertThat(visitor.getQuery().toString(),equalTo("name:word"));
}
Class: org.apache.cxf.jaxrs.ext.search.odata.ODataParserTest BooleanVerifier InternalCallVerifier
@Test public void testFilterByFirstNameEqualsValueNonMatchingProperty() throws SearchParseException {
SearchCondition filter=parser.parse("thename eq 'Tom'");
assertTrue(filter.isMet(new Person("Tom","Bombadil")));
assertFalse(filter.isMet(new Person("Peter","Bombadil")));
}
BooleanVerifier InternalCallVerifier
@Test public void testFilterBySsnNotEqualsToValue() throws SearchParseException {
SearchCondition filter=parser.parse("Ssn ne 748232221");
assertTrue(filter.isMet(new Person("Tom","Bombadil").withSsn(553232222L)));
assertFalse(filter.isMet(new Person("Tom","Bombadil").withHourlyRate(748232221L)));
}
BooleanVerifier InternalCallVerifier
@Test public void testFilterByFirstOrLastNameEqualValue() throws SearchParseException {
SearchCondition filter=parser.parse("FirstName eq 'Tom' or FirstName eq 'Peter' and LastName eq 'Bombadil'");
assertTrue(filter.isMet(new Person("Tom","Bombadil")));
assertTrue(filter.isMet(new Person("Peter","Bombadil")));
assertFalse(filter.isMet(new Person("Barry","Bombadil")));
}
BooleanVerifier InternalCallVerifier
@Test public void testFilterByFirstAndLastNameEqualValue() throws SearchParseException {
SearchCondition filter=parser.parse("FirstName eq 'Tom' and LastName eq 'Bombadil'");
assertTrue(filter.isMet(new Person("Tom","Bombadil")));
assertFalse(filter.isMet(new Person("Peter","Bombadil")));
}
BooleanVerifier InternalCallVerifier
@Test public void testFilterByHeightGreatOrEqualValue() throws SearchParseException {
SearchCondition filter=parser.parse("Height ge 179.5f or Height le 159.5d");
assertTrue(filter.isMet(new Person("Tom","Bombadil").withHeight(185.6f)));
assertFalse(filter.isMet(new Person("Tom","Bombadil").withHeight(166.7f)));
}
BooleanVerifier InternalCallVerifier
@Test public void testFilterByValueEqualsFirstName() throws SearchParseException {
SearchCondition filter=parser.parse("'Tom' eq FirstName");
assertTrue(filter.isMet(new Person("Tom","Bombadil")));
}
BooleanVerifier InternalCallVerifier
@Test public void testFilterByHourlyRateGreatThanValue() throws SearchParseException {
SearchCondition filter=parser.parse("HourlyRate ge 30.50d or HourlyRate lt 20.50f");
assertTrue(filter.isMet(new Person("Tom","Bombadil").withHourlyRate(45.6)));
assertFalse(filter.isMet(new Person("Tom","Bombadil").withHourlyRate(26.7)));
}
BooleanVerifier InternalCallVerifier
@Test public void testFilterByFirstAndLastNameEqualValueWithAlternative() throws SearchParseException {
SearchCondition filter=parser.parse("(FirstName eq 'Tom' and LastName eq 'Tommyknocker')" + " or (FirstName eq 'Peter' and LastName eq 'Bombadil')");
assertTrue(filter.isMet(new Person("Tom","Tommyknocker")));
assertTrue(filter.isMet(new Person("Peter","Bombadil")));
assertFalse(filter.isMet(new Person("Tom","Bombadil")));
}
BooleanVerifier InternalCallVerifier
@Test public void testFilterByFirstNameEqualsValue() throws SearchParseException {
SearchCondition filter=parser.parse("FirstName eq 'Tom'");
assertTrue(filter.isMet(new Person("Tom","Bombadil")));
assertFalse(filter.isMet(new Person("Peter","Bombadil")));
}
BooleanVerifier InternalCallVerifier
@Test public void testFilterByAgeGreatThanValue() throws SearchParseException {
SearchCondition filter=parser.parse("Age gt 17");
assertTrue(filter.isMet(new Person("Tom","Bombadil").withAge(18)));
assertFalse(filter.isMet(new Person("Tom","Bombadil").withAge(16)));
}
Class: org.apache.cxf.jaxrs.ext.search.sql.SQLPrinterVisitorTest BooleanVerifier InternalCallVerifier
@Test public void testSQL1WithSearchBean() throws SearchParseException {
FiqlParser beanParser=new FiqlParser(SearchBean.class);
SearchCondition filter=beanParser.parse("name==ami*;level=gt=10");
SQLPrinterVisitor visitor=new SQLPrinterVisitor("table");
filter.accept(visitor);
String sql=visitor.getQuery();
assertTrue("SELECT * FROM table WHERE (name LIKE 'ami%') AND (level > '10')".equals(sql) || "SELECT * FROM table WHERE (level > '10') AND (name LIKE 'ami%')".equals(sql));
}
BooleanVerifier InternalCallVerifier
@Test public void testSQLCamelNameSearchBean() throws SearchParseException {
FiqlParser beanParser=new FiqlParser(SearchBean.class);
SearchCondition filter=beanParser.parse("theName==ami*;theLevel=gt=10");
SQLPrinterVisitor visitor=new SQLPrinterVisitor("table");
filter.accept(visitor);
String sql=visitor.getQuery();
assertTrue("SELECT * FROM table WHERE (theName LIKE 'ami%') AND (theLevel > '10')".equals(sql) || "SELECT * FROM table WHERE (theLevel > '10') AND (theName LIKE 'ami%')".equals(sql));
}
BooleanVerifier InternalCallVerifier
@Test public void testSQL5WithColumns() throws SearchParseException {
SearchCondition filter=parser.parse("name==test");
SQLPrinterVisitor visitor=new SQLPrinterVisitor("table","NAMES");
filter.accept(visitor);
String sql=visitor.getQuery();
assertTrue("SELECT NAMES FROM table WHERE name = 'test'".equals(sql));
}
BooleanVerifier InternalCallVerifier
@Test public void testSQL3WithSearchBean() throws SearchParseException {
FiqlParser beanParser=new FiqlParser(SearchBean.class);
SearchCondition filter=beanParser.parse("name==foo*;(name!=*bar,level=gt=10)");
SQLPrinterVisitor visitor=new SQLPrinterVisitor("table");
filter.accept(visitor);
String sql=visitor.getQuery();
assertTrue(("SELECT * FROM table WHERE (name LIKE 'foo%') AND ((name NOT LIKE '%bar') " + "OR (level > '10'))").equals(sql) || ("SELECT * FROM table WHERE (name LIKE 'foo%') AND " + "((level > '10') OR (name NOT LIKE '%bar'))").equals(sql));
}
BooleanVerifier InternalCallVerifier
@Test public void testSQL5WithFieldMap() throws SearchParseException {
SearchCondition filter=parser.parse("name==test");
SQLPrinterVisitor visitor=new SQLPrinterVisitor(Collections.singletonMap("name","NAMES"),"table",Collections.singletonList("NAMES"));
filter.accept(visitor);
String sql=visitor.getQuery();
assertTrue("SELECT NAMES FROM table WHERE NAMES = 'test'".equals(sql));
}
BooleanVerifier InternalCallVerifier
@Test public void testSQL5() throws SearchParseException {
SearchCondition filter=parser.parse("name==test");
SQLPrinterVisitor visitor=new SQLPrinterVisitor("table");
filter.accept(visitor);
String sql=visitor.getQuery();
assertTrue("SELECT * FROM table WHERE name = 'test'".equals(sql));
}
BooleanVerifier InternalCallVerifier
@Test public void testSQL4() throws SearchParseException {
SearchCondition filter=parser.parse("(name==test,level==18);(name==test1,level!=19)");
SQLPrinterVisitor visitor=new SQLPrinterVisitor("table");
filter.accept(visitor);
String sql=visitor.getQuery();
assertTrue(("SELECT * FROM table WHERE ((name = 'test') OR (level = '18'))" + " AND ((name = 'test1') OR (level <> '19'))").equals(sql) || ("SELECT * FROM table WHERE ((name = 'test1') OR (level <> '19'))" + " AND ((name = 'test') OR (level = '18'))").equals(sql));
}
BooleanVerifier InternalCallVerifier
@Test public void testSQL3() throws SearchParseException {
SearchCondition filter=parser.parse("name==foo*;(name!=*bar,level=gt=10)");
SQLPrinterVisitor visitor=new SQLPrinterVisitor("table");
filter.accept(visitor);
String sql=visitor.getQuery();
assertTrue(("SELECT * FROM table WHERE (name LIKE 'foo%') AND ((name NOT LIKE '%bar') " + "OR (level > '10'))").equals(sql) || ("SELECT * FROM table WHERE (name LIKE 'foo%') AND " + "((level > '10') OR (name NOT LIKE '%bar'))").equals(sql));
}
BooleanVerifier InternalCallVerifier
@Test public void testSQL2() throws SearchParseException {
SearchCondition filter=parser.parse("name==ami*,level=gt=10");
SQLPrinterVisitor visitor=new SQLPrinterVisitor("table");
filter.accept(visitor);
String sql=visitor.getQuery();
assertTrue("SELECT * FROM table WHERE (name LIKE 'ami%') OR (level > '10')".equals(sql) || "SELECT * FROM table WHERE (level > '10') OR (name LIKE 'ami%')".equals(sql));
}
BooleanVerifier InternalCallVerifier
@Test public void testSQL4WithTLStateAndSingleThread() throws SearchParseException {
SearchCondition filter=parser.parse("(name==test,level==18);(name==test1,level!=19)");
SQLPrinterVisitor visitor=new SQLPrinterVisitor("table");
visitor.setVisitorState(new SBThreadLocalVisitorState());
filter.accept(visitor);
String sql=visitor.getQuery();
assertTrue(("SELECT * FROM table WHERE ((name = 'test') OR (level = '18'))" + " AND ((name = 'test1') OR (level <> '19'))").equals(sql) || ("SELECT * FROM table WHERE ((name = 'test1') OR (level <> '19'))" + " AND ((name = 'test') OR (level = '18'))").equals(sql));
}
BooleanVerifier InternalCallVerifier
@Test public void testSQL1() throws SearchParseException {
SearchCondition filter=parser.parse("name==ami%*;level=gt=10");
SQLPrinterVisitor visitor=new SQLPrinterVisitor("table");
filter.accept(visitor.visitor());
String sql=visitor.getQuery();
assertTrue("SELECT * FROM table WHERE (name LIKE 'ami\\%%') AND (level > '10')".equals(sql) || "SELECT * FROM table WHERE (level > '10') AND (name LIKE 'ami\\%%')".equals(sql));
}
Class: org.apache.cxf.jaxrs.ext.search.tika.TikaContentExtractorTest BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testExtractedTextContentDoesNotMatchSearchCriteria() throws Exception {
SearchCondition sc=parser.parse("Author==Barry*");
final SearchBean bean=extractor.extractMetadataToSearchBean(getClass().getResourceAsStream("/files/testPDF.pdf"));
assertNotNull("Document should not be null",bean);
assertFalse(sc.isMet(bean));
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testExtractedTextContentMatchesSearchCriteria() throws Exception {
SearchCondition sc=parser.parse("Author==Bertrand*");
final SearchBean bean=extractor.extractMetadataToSearchBean(getClass().getResourceAsStream("/files/testPDF.pdf"));
assertNotNull("Document should not be null",bean);
assertTrue(sc.isMet(bean));
}
Class: org.apache.cxf.jaxrs.ext.search.tika.TikaLuceneContentExtractorTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testExtractedTextContentMatchesTypesAndLongSearchCriteria() throws Exception {
final LuceneDocumentMetadata documentMetadata=new LuceneDocumentMetadata("contents").withField("xmpTPg:NPages",Long.class);
final Document document=extractor.extract(getClass().getResourceAsStream("/files/testPDF.pdf"),documentMetadata);
assertNotNull("Document should not be null",document);
writer.addDocument(document);
writer.commit();
assertEquals(1,getHits("xmpTPg:NPages=gt=0",documentMetadata.getFieldTypes()).length);
assertEquals(1,getHits("xmpTPg:NPages==1",documentMetadata.getFieldTypes()).length);
assertEquals(1,getHits("xmpTPg:NPages=ge=1",documentMetadata.getFieldTypes()).length);
assertEquals(0,getHits("xmpTPg:NPages=gt=1",documentMetadata.getFieldTypes()).length);
assertEquals(0,getHits("xmpTPg:NPages=lt=1",documentMetadata.getFieldTypes()).length);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testExtractedTextContentMatchesTypesAndIntegerSearchCriteria() throws Exception {
final LuceneDocumentMetadata documentMetadata=new LuceneDocumentMetadata("contents").withField("xmpTPg:NPages",Integer.class);
final Document document=extractor.extract(getClass().getResourceAsStream("/files/testPDF.pdf"),documentMetadata);
assertNotNull("Document should not be null",document);
writer.addDocument(document);
writer.commit();
assertEquals(1,getHits("xmpTPg:NPages=gt=0",documentMetadata.getFieldTypes()).length);
assertEquals(1,getHits("xmpTPg:NPages==1",documentMetadata.getFieldTypes()).length);
assertEquals(1,getHits("xmpTPg:NPages=ge=1",documentMetadata.getFieldTypes()).length);
assertEquals(0,getHits("xmpTPg:NPages=gt=1",documentMetadata.getFieldTypes()).length);
assertEquals(0,getHits("xmpTPg:NPages=lt=1",documentMetadata.getFieldTypes()).length);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testExtractedTextContentMatchesTypesAndDateSearchCriteria() throws Exception {
final LuceneDocumentMetadata documentMetadata=new LuceneDocumentMetadata("contents").withField("modified",Date.class);
final Document document=extractor.extract(getClass().getResourceAsStream("/files/testPDF.pdf"),documentMetadata);
assertNotNull("Document should not be null",document);
writer.addDocument(document);
writer.commit();
assertEquals(1,getHits("modified=gt=2007-09-14T09:02:31Z",documentMetadata.getFieldTypes()).length);
assertEquals(1,getHits("modified=le=2007-09-15T09:02:31-0500",documentMetadata.getFieldTypes()).length);
assertEquals(1,getHits("modified=ge=2007-09-15",documentMetadata.getFieldTypes()).length);
assertEquals(1,getHits("modified==2007-09-15",documentMetadata.getFieldTypes()).length);
assertEquals(0,getHits("modified==2007-09-16",documentMetadata.getFieldTypes()).length);
assertEquals(0,getHits("modified=gt=2007-09-16",documentMetadata.getFieldTypes()).length);
assertEquals(0,getHits("modified=lt=2007-09-15",documentMetadata.getFieldTypes()).length);
assertEquals(0,getHits("modified=gt=2007-09-16T09:02:31",documentMetadata.getFieldTypes()).length);
assertEquals(0,getHits("modified=lt=2007-09-01T09:02:31",documentMetadata.getFieldTypes()).length);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testContentSourceMatchesSearchCriteria() throws Exception {
final LuceneDocumentMetadata documentMetadata=new LuceneDocumentMetadata().withSource("testPDF.pdf");
final Document document=extractor.extract(getClass().getResourceAsStream("/files/testPDF.pdf"),documentMetadata);
assertNotNull("Document should not be null",document);
writer.addDocument(document);
writer.commit();
assertEquals(1,getHits("source==testPDF.pdf").length);
assertEquals(0,getHits("source==testPDF").length);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testExtractedTextContentMatchesSearchCriteria() throws Exception {
final Document document=extractor.extract(getClass().getResourceAsStream("/files/testPDF.pdf"));
assertNotNull("Document should not be null",document);
writer.addDocument(document);
writer.commit();
assertEquals(1,getHits("ct==tika").length);
assertEquals(1,getHits("ct==incubation").length);
assertEquals(0,getHits("ct==toolsuite").length);
assertEquals(1,getHits("Author==Bertrand*").length);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testExtractedTextContentMatchesTypesAndDoubleSearchCriteria() throws Exception {
final LuceneDocumentMetadata documentMetadata=new LuceneDocumentMetadata("contents").withField("xmpTPg:NPages",Double.class);
final Document document=extractor.extract(getClass().getResourceAsStream("/files/testPDF.pdf"),documentMetadata);
assertNotNull("Document should not be null",document);
writer.addDocument(document);
writer.commit();
assertEquals(1,getHits("xmpTPg:NPages=gt=0.0",documentMetadata.getFieldTypes()).length);
assertEquals(1,getHits("xmpTPg:NPages==1.0",documentMetadata.getFieldTypes()).length);
assertEquals(1,getHits("xmpTPg:NPages=ge=1.0",documentMetadata.getFieldTypes()).length);
assertEquals(0,getHits("xmpTPg:NPages=gt=1.0",documentMetadata.getFieldTypes()).length);
assertEquals(0,getHits("xmpTPg:NPages=lt=1.0",documentMetadata.getFieldTypes()).length);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testExtractedTextContentMatchesTypesAndFloatSearchCriteria() throws Exception {
final LuceneDocumentMetadata documentMetadata=new LuceneDocumentMetadata("contents").withField("xmpTPg:NPages",Float.class);
final Document document=extractor.extract(getClass().getResourceAsStream("/files/testPDF.pdf"),documentMetadata);
assertNotNull("Document should not be null",document);
writer.addDocument(document);
writer.commit();
assertEquals(1,getHits("xmpTPg:NPages=gt=0.0",documentMetadata.getFieldTypes()).length);
assertEquals(1,getHits("xmpTPg:NPages==1.0",documentMetadata.getFieldTypes()).length);
assertEquals(1,getHits("xmpTPg:NPages=ge=1.0",documentMetadata.getFieldTypes()).length);
assertEquals(0,getHits("xmpTPg:NPages=gt=1.0",documentMetadata.getFieldTypes()).length);
assertEquals(0,getHits("xmpTPg:NPages=lt=1.0",documentMetadata.getFieldTypes()).length);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testExtractedTextContentMatchesTypesAndByteSearchCriteria() throws Exception {
final LuceneDocumentMetadata documentMetadata=new LuceneDocumentMetadata("contents").withField("xmpTPg:NPages",Byte.class);
final Document document=extractor.extract(getClass().getResourceAsStream("/files/testPDF.pdf"),documentMetadata);
assertNotNull("Document should not be null",document);
writer.addDocument(document);
writer.commit();
assertEquals(1,getHits("xmpTPg:NPages=gt=0",documentMetadata.getFieldTypes()).length);
assertEquals(1,getHits("xmpTPg:NPages==1",documentMetadata.getFieldTypes()).length);
assertEquals(1,getHits("xmpTPg:NPages=ge=1",documentMetadata.getFieldTypes()).length);
assertEquals(0,getHits("xmpTPg:NPages=gt=1",documentMetadata.getFieldTypes()).length);
assertEquals(0,getHits("xmpTPg:NPages=lt=1",documentMetadata.getFieldTypes()).length);
}
Class: org.apache.cxf.jaxrs.ext.xml.XMLSourceTest InternalCallVerifier NullVerifier
@Test public void testGetNodeAsElement(){
InputStream is=new ByteArrayInputStream(" ".getBytes());
XMLSource xp=new XMLSource(is);
xp.setBuffering();
Element element=xp.getNode("/foo/bar",Element.class);
assertNotNull(element);
}
InternalCallVerifier EqualityVerifier
@Test public void testGetStringValue(){
InputStream is=new ByteArrayInputStream(" ".getBytes());
XMLSource xp=new XMLSource(is);
String value=xp.getValue("/foo/bar/@id");
assertEquals("2",value);
}
InternalCallVerifier EqualityVerifier
@Test public void testGetRelativeLink(){
InputStream is=new ByteArrayInputStream(" ".getBytes());
XMLSource xp=new XMLSource(is);
URI value=xp.getLink("/foo/bar/@href");
assertEquals("/2",value.toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testAttributeValue(){
InputStream is=new ByteArrayInputStream("barValue ".getBytes());
XMLSource xp=new XMLSource(is);
xp.setBuffering();
assertEquals("baz",xp.getValue("/foo/bar/@attr"));
}
InternalCallVerifier NullVerifier
@Test public void testGetNodeNoNamespace(){
InputStream is=new ByteArrayInputStream(" ".getBytes());
XMLSource xp=new XMLSource(is);
xp.setBuffering();
Bar bar=xp.getNode("/foo/bar",Bar.class);
assertNotNull(bar);
}
InternalCallVerifier EqualityVerifier
@Test public void testBaseURI(){
InputStream is=new ByteArrayInputStream(" ".getBytes());
XMLSource xp=new XMLSource(is);
URI value=xp.getBaseURI();
assertEquals("http://bar",value.toString());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetNodeAsJaxbElement(){
InputStream is=new ByteArrayInputStream(" ".getBytes());
XMLSource xp=new XMLSource(is);
xp.setBuffering();
Bar3 bar=xp.getNode("/foo/bar",Bar3.class);
assertNotNull(bar);
assertEquals("foo",bar.getName());
}
InternalCallVerifier NullVerifier
@Test public void testGetNodeAsSource(){
InputStream is=new ByteArrayInputStream(" ".getBytes());
XMLSource xp=new XMLSource(is);
xp.setBuffering();
Source element=xp.getNode("/foo/bar",Source.class);
assertNotNull(element);
}
APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testGetNodeBuffering(){
String data=" ";
InputStream is=new ByteArrayInputStream(data.getBytes());
XMLSource xp=new XMLSource(is);
xp.setBuffering();
Map map=new LinkedHashMap();
map.put("x","http://baz");
Bar2 bar=xp.getNode("/x:foo/x:bar",map,Bar2.class);
assertNotNull(bar);
bar=xp.getNode("/x:foo/x:bar",map,Bar2.class);
assertNotNull(bar);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testIntegerValues(){
InputStream is=new ByteArrayInputStream(" ".getBytes());
XMLSource xp=new XMLSource(is);
xp.setBuffering();
Integer[] values=xp.getNodes("/foo/bar/@attr",Integer.class);
assertEquals(2,values.length);
assertTrue(values[0] == 1 && values[1] == 2 || values[0] == 2 && values[1] == 1);
}
APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testGetNodeDefaultNamespace(){
String data=" ";
InputStream is=new ByteArrayInputStream(data.getBytes());
XMLSource xp=new XMLSource(is);
xp.setBuffering();
Map map=new LinkedHashMap();
map.put("x","http://baz");
Bar2 bar=xp.getNode("/x:foo/x:bar",map,Bar2.class);
assertNotNull(bar);
}
BooleanVerifier InternalCallVerifier
@Test public void testNodeStringValue(){
InputStream is=getClass().getResourceAsStream("/book1.xsd");
XMLSource xp=new XMLSource(is);
xp.setBuffering();
Map nsMap=Collections.singletonMap("xs",Constants.URI_2001_SCHEMA_XSD);
String value=xp.getNode("/xs:schema",nsMap,String.class);
assertFalse(value.contains("
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetNodesNamespace(){
String data=" ";
InputStream is=new ByteArrayInputStream(data.getBytes());
XMLSource xp=new XMLSource(is);
xp.setBuffering();
Map map=new LinkedHashMap();
map.put("x","http://baz");
Bar2[] bars=xp.getNodes("/x:foo/x:bar",map,Bar2.class);
assertNotNull(bars);
assertNotNull(bars);
assertEquals(2,bars.length);
assertNotSame(bars[0],bars[1]);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testNodeTextValues(){
InputStream is=new ByteArrayInputStream("bar1 bar2 ".getBytes());
XMLSource xp=new XMLSource(is);
xp.setBuffering();
List values=Arrays.asList(xp.getValues("/foo/bar/text()"));
assertEquals(2,values.size());
assertTrue(values.contains("bar1"));
assertTrue(values.contains("bar2"));
}
APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testGetNodeNamespace3(){
String data=" ";
InputStream is=new ByteArrayInputStream(data.getBytes());
XMLSource xp=new XMLSource(is);
xp.setBuffering();
Map map=new LinkedHashMap();
map.put("x","http://foo");
map.put("y","http://baz");
Bar2 bar=xp.getNode("/x:foo/y:bar",map,Bar2.class);
assertNotNull(bar);
}
InternalCallVerifier NullVerifier
@Test public void testGetNodeNull(){
InputStream is=new ByteArrayInputStream(" ".getBytes());
XMLSource xp=new XMLSource(is);
xp.setBuffering();
assertNull(xp.getNode("/foo/bar1",Element.class));
}
APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testGetNodeNamespace2(){
String data=" ";
InputStream is=new ByteArrayInputStream(data.getBytes());
XMLSource xp=new XMLSource(is);
xp.setBuffering();
Map map=new LinkedHashMap();
map.put("x","http://baz");
Bar2 bar=xp.getNode("/x:foo/x:bar",map,Bar2.class);
assertNotNull(bar);
}
InternalCallVerifier EqualityVerifier
@Test public void testNodeTextValue(){
InputStream is=new ByteArrayInputStream("barValue ".getBytes());
XMLSource xp=new XMLSource(is);
xp.setBuffering();
assertEquals("barValue",xp.getValue("/foo/bar"));
}
APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testGetNodeNamespace(){
String data=" ";
InputStream is=new ByteArrayInputStream(data.getBytes());
XMLSource xp=new XMLSource(is);
xp.setBuffering();
Map map=new LinkedHashMap();
map.put("x","http://baz");
Bar2 bar=xp.getNode("/x:foo/x:bar",map,Bar2.class);
assertNotNull(bar);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testAttributeValues(){
InputStream is=new ByteArrayInputStream("bar1 bar2 ".getBytes());
XMLSource xp=new XMLSource(is);
xp.setBuffering();
List values=Arrays.asList(xp.getValues("/foo/bar/@attr"));
assertEquals(2,values.size());
assertTrue(values.contains("baz"));
assertTrue(values.contains("baz2"));
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testAttributeValueAsNode(){
InputStream is=new ByteArrayInputStream("barValue ".getBytes());
XMLSource xp=new XMLSource(is);
xp.setBuffering();
Node node=xp.getNode("/foo/bar/@attr",Node.class);
assertNotNull(node);
assertEquals("baz",node.getTextContent());
}
InternalCallVerifier IdentityVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetNodesNoNamespace(){
InputStream is=new ByteArrayInputStream(" ".getBytes());
XMLSource xp=new XMLSource(is);
xp.setBuffering();
Bar[] bars=xp.getNodes("/foo/bar",Bar.class);
assertNotNull(bars);
assertEquals(2,bars.length);
assertNotSame(bars[0],bars[1]);
}
Class: org.apache.cxf.jaxrs.impl.CacheControlHeaderProviderTest BooleanVerifier InternalCallVerifier
@Test public void testFromSimpleString(){
CacheControl c=CacheControl.valueOf("public,must-revalidate");
assertTrue(!c.isPrivate() && !c.isNoStore() && c.isMustRevalidate()&& !c.isProxyRevalidate());
assertTrue(!c.isNoCache() && !c.isNoTransform() && c.getNoCacheFields().size() == 0 && c.getPrivateFields().size() == 0);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testReadMultiplePrivateAndNoCacheFields(){
String s="private=\"foo1,foo2\",no-store,no-transform," + "must-revalidate,proxy-revalidate,max-age=2,s-maxage=3,no-cache=\"bar1,bar2\"," + "ext=1";
CacheControl cc=CacheControl.valueOf(s);
assertTrue(cc.isPrivate());
List privateFields=cc.getPrivateFields();
assertEquals(2,privateFields.size());
assertEquals("foo1",privateFields.get(0));
assertEquals("foo2",privateFields.get(1));
assertTrue(cc.isNoCache());
List noCacheFields=cc.getNoCacheFields();
assertEquals(2,noCacheFields.size());
assertEquals("bar1",noCacheFields.get(0));
assertEquals("bar2",noCacheFields.get(1));
assertTrue(cc.isNoStore());
assertTrue(cc.isNoTransform());
assertTrue(cc.isMustRevalidate());
assertTrue(cc.isProxyRevalidate());
assertEquals(2,cc.getMaxAge());
assertEquals(3,cc.getSMaxAge());
Map exts=cc.getCacheExtension();
assertEquals(1,exts.size());
assertEquals("1",exts.get("ext"));
}
BooleanVerifier InternalCallVerifier
@Test public void testMultiplePrivateFields(){
CacheControl cc=new CacheControl();
cc.setPrivate(true);
cc.getPrivateFields().add("a");
cc.getPrivateFields().add("b");
assertTrue(cc.toString().contains("private=\"a,b\""));
}
BooleanVerifier InternalCallVerifier
@Test public void testMultipleNoCacheFields(){
CacheControl cc=new CacheControl();
cc.setNoCache(true);
cc.getNoCacheFields().add("c");
cc.getNoCacheFields().add("d");
assertTrue(cc.toString().contains("no-cache=\"c,d\""));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testFromComplexString(){
CacheControl c=CacheControl.valueOf("private=\"foo\",no-cache=\"bar\",no-store,no-transform," + "must-revalidate,proxy-revalidate,max-age=2,s-maxage=3");
assertTrue(c.isPrivate() && c.isNoStore() && c.isMustRevalidate()&& c.isProxyRevalidate()&& c.isNoCache());
assertTrue(c.isNoTransform() && c.getNoCacheFields().size() == 1 && c.getPrivateFields().size() == 1);
assertEquals("foo",c.getPrivateFields().get(0));
assertEquals("bar",c.getNoCacheFields().get(0));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testFromComplexStringWithSemicolon(){
CacheControlHeaderProvider cp=new CacheControlHeaderProvider(){
protected Message getCurrentMessage(){
Message m=new MessageImpl();
m.put(CacheControlHeaderProvider.CACHE_CONTROL_SEPARATOR_PROPERTY,";");
return m;
}
}
;
CacheControl c=cp.fromString("private=\"foo\";no-cache=\"bar\";no-store;no-transform;" + "must-revalidate;proxy-revalidate;max-age=2;s-maxage=3");
assertTrue(c.isPrivate() && c.isNoStore() && c.isMustRevalidate()&& c.isProxyRevalidate()&& c.isNoCache());
assertTrue(c.isNoTransform() && c.getNoCacheFields().size() == 1 && c.getPrivateFields().size() == 1);
assertEquals("foo",c.getPrivateFields().get(0));
assertEquals("bar",c.getNoCacheFields().get(0));
}
InternalCallVerifier EqualityVerifier
@Test public void testNoCacheEnabled(){
CacheControl cc=new CacheControl();
cc.setNoCache(true);
assertEquals("no-cache,no-transform",cc.toString());
}
BooleanVerifier InternalCallVerifier
@Test public void testCacheExtensionToString(){
CacheControl cc=new CacheControl();
cc.getCacheExtension().put("ext1",null);
cc.getCacheExtension().put("ext2","value2");
cc.getCacheExtension().put("ext3","value 3");
String value=cc.toString();
assertTrue(value.indexOf("ext1") != -1 && value.indexOf("ext1=") == -1);
assertTrue(value.indexOf("ext2=value2") != -1);
assertTrue(value.indexOf("ext3=\"value 3\"") != -1);
}
InternalCallVerifier EqualityVerifier
@Test public void testNoCacheDisabled(){
CacheControl cc=new CacheControl();
cc.setNoCache(false);
assertEquals("no-transform",cc.toString());
}
Class: org.apache.cxf.jaxrs.impl.ConfigurationImplTest BooleanVerifier InternalCallVerifier
@Test public void testIsRegistered(){
ConfigurationImpl c=new ConfigurationImpl(RuntimeType.SERVER);
ContainerResponseFilter filter=new ContainerResponseFilterImpl();
assertTrue(c.register(filter,Collections.,Integer>singletonMap(ContainerResponseFilter.class,1000)));
assertTrue(c.isRegistered(filter));
assertTrue(c.isRegistered(ContainerResponseFilterImpl.class));
assertFalse(c.isRegistered(ContainerResponseFilter.class));
assertFalse(c.register(filter,Collections.,Integer>singletonMap(ContainerResponseFilter.class,1000)));
assertFalse(c.register(ContainerResponseFilterImpl.class,Collections.,Integer>singletonMap(ContainerResponseFilter.class,1000)));
}
Class: org.apache.cxf.jaxrs.impl.DateHeaderProviderTest InternalCallVerifier EqualityVerifier
@Test public void testToFromSimpleString(){
Date retry=new Date();
ServiceUnavailableException ex=new ServiceUnavailableException(retry);
Date retry2=ex.getRetryTime(new Date());
assertEquals(HttpUtils.toHttpDate(retry),HttpUtils.toHttpDate(retry2));
}
Class: org.apache.cxf.jaxrs.impl.EvaluatePreconditionsTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testIfNoneMatchIfModified200(){
final Request request=getRequest(HttpHeaders.IF_MODIFIED_SINCE,DATE_FMT_822.format(DATE_OLD),HttpHeaders.IF_NONE_MATCH,ETAG_NEW.toString());
final Response response=service.perform(request);
Assert.assertEquals(HttpServletResponse.SC_OK,response.getStatus());
}
InternalCallVerifier EqualityVerifier
@Test public void testIfNoneMatch200(){
final Request request=getRequest(HttpHeaders.IF_NONE_MATCH,ETAG_NEW.toString());
final Response response=service.perform(request);
Assert.assertEquals(HttpServletResponse.SC_OK,response.getStatus());
}
InternalCallVerifier EqualityVerifier
@Test public void testIfNoneMatch304(){
final Request request=getRequest(HttpHeaders.IF_NONE_MATCH,ETAG_OLD.toString());
final Response response=service.perform(request);
Assert.assertEquals(HttpServletResponse.SC_NOT_MODIFIED,response.getStatus());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testIfModified304(){
final Request request=getRequest(HttpHeaders.IF_MODIFIED_SINCE,DATE_FMT_822.format(DATE_NEW));
final Response response=service.perform(request);
Assert.assertEquals(HttpServletResponse.SC_NOT_MODIFIED,response.getStatus());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testIfNoneMatchIfModified304(){
final Request request=getRequest(HttpHeaders.IF_MODIFIED_SINCE,DATE_FMT_822.format(DATE_OLD),HttpHeaders.IF_NONE_MATCH,ETAG_OLD.toString());
final Response response=service.perform(request);
Assert.assertEquals(HttpServletResponse.SC_NOT_MODIFIED,response.getStatus());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testIfModified200(){
service.setLastModified(DATE_NEW);
final Request request=getRequest(HttpHeaders.IF_MODIFIED_SINCE,DATE_FMT_822.format(DATE_OLD));
final Response response=service.perform(request);
Assert.assertEquals(HttpServletResponse.SC_OK,response.getStatus());
}
InternalCallVerifier EqualityVerifier
@Test public void testUnconditional200(){
final Request request=getRequest();
final Response response=service.perform(request);
Assert.assertEquals(HttpServletResponse.SC_OK,response.getStatus());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testIfNoneMatchIfModified200Two(){
service.setLastModified(DATE_NEW);
final Request request=getRequest(HttpHeaders.IF_MODIFIED_SINCE,DATE_FMT_822.format(DATE_OLD),HttpHeaders.IF_NONE_MATCH,ETAG_NEW.toString());
final Response response=service.perform(request);
Assert.assertEquals(HttpServletResponse.SC_OK,response.getStatus());
}
Class: org.apache.cxf.jaxrs.impl.HttpHeadersImplTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetHeaderNameValue() throws Exception {
Message m=control.createMock(Message.class);
m.get(Message.PROTOCOL_HEADERS);
MetadataMap headers=createHeader("COMPLEX_HEADER","b=c; param=c, a=b;param=b");
EasyMock.expectLastCall().andReturn(headers);
m.getContextualProperty("org.apache.cxf.http.header.split");
EasyMock.expectLastCall().andReturn("true");
control.replay();
HttpHeaders h=new HttpHeadersImpl(m);
List values=h.getRequestHeader("COMPLEX_HEADER");
assertNotNull(values);
assertEquals(2,values.size());
assertEquals("b=c; param=c",values.get(0));
assertEquals("a=b;param=b",values.get(1));
}
InternalCallVerifier EqualityVerifier
@Test public void testGetNoMediaTypes() throws Exception {
Message m=control.createMock(Message.class);
m.get(Message.PROTOCOL_HEADERS);
EasyMock.expectLastCall().andReturn(Collections.emptyMap());
control.replay();
HttpHeaders h=new HttpHeadersImpl(m);
List acceptValues=h.getAcceptableMediaTypes();
assertEquals(1,acceptValues.size());
assertEquals("*/*",acceptValues.get(0).toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetNoLanguages() throws Exception {
Message m=control.createMock(Message.class);
m.get(Message.PROTOCOL_HEADERS);
EasyMock.expectLastCall().andReturn(Collections.emptyMap());
control.replay();
HttpHeaders h=new HttpHeadersImpl(m);
List locales=h.getAcceptableLanguages();
assertEquals(1,locales.size());
assertEquals("*",locales.get(0).toString());
}
BooleanVerifier InternalCallVerifier
@Test public void testGetEmptyHeader() throws Exception {
Message m=new MessageImpl();
Map> headers=new TreeMap>(String.CASE_INSENSITIVE_ORDER);
headers.put("A",Collections.emptyList());
m.put(Message.PROTOCOL_HEADERS,headers);
HttpHeaders h=new HttpHeadersImpl(m);
List values=h.getRequestHeader("A");
assertTrue(values.isEmpty());
}
InternalCallVerifier EqualityVerifier
@Test public void testSingleAcceptableLanguages() throws Exception {
Message m=control.createMock(Message.class);
m.get(Message.PROTOCOL_HEADERS);
MetadataMap headers=createHeaders();
headers.putSingle(HttpHeaders.ACCEPT_LANGUAGE,"en");
EasyMock.expectLastCall().andReturn(headers);
control.replay();
HttpHeaders h=new HttpHeadersImpl(m);
List languages=h.getAcceptableLanguages();
assertEquals(1,languages.size());
assertEquals(new Locale("en"),languages.get(0));
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetHeaderWithQuotes1() throws Exception {
Message m=control.createMock(Message.class);
m.getContextualProperty("org.apache.cxf.http.header.split");
EasyMock.expectLastCall().andReturn("true");
m.get(Message.PROTOCOL_HEADERS);
MetadataMap headers=createHeader("COMPLEX_HEADER","a1=\"a\", a2=\"a\";param, b, b;param, c1=\"c, d, e\", " + "c2=\"c, d, e\";param, a=b, a=b;p=p1, a2=\"a\";param=p," + "a3=\"a\";param=\"p,b\"");
EasyMock.expectLastCall().andReturn(headers);
control.replay();
HttpHeaders h=new HttpHeadersImpl(m);
List values=h.getRequestHeader("COMPLEX_HEADER");
assertNotNull(values);
assertEquals(10,values.size());
assertEquals("a1=\"a\"",values.get(0));
assertEquals("a2=\"a\";param",values.get(1));
assertEquals("b",values.get(2));
assertEquals("b;param",values.get(3));
assertEquals("c1=\"c, d, e\"",values.get(4));
assertEquals("c2=\"c, d, e\";param",values.get(5));
assertEquals("a=b",values.get(6));
assertEquals("a=b;p=p1",values.get(7));
assertEquals("a2=\"a\";param=p",values.get(8));
assertEquals("a3=\"a\";param=\"p,b\"",values.get(9));
}
InternalCallVerifier EqualityVerifier
@Test public void testGetHeaderString2() throws Exception {
Message m=new MessageImpl();
m.put(Message.PROTOCOL_HEADERS,createHeaders());
HttpHeaders h=new HttpHeadersImpl(m);
String date=h.getHeaderString("a");
assertEquals("1,2",date);
}
InternalCallVerifier EqualityVerifier
@Test public void testGetHeader2() throws Exception {
Message m=new MessageImpl();
m.put(Message.PROTOCOL_HEADERS,createHeaders());
HttpHeaders h=new HttpHeadersImpl(m);
List values=h.getRequestHeader("a");
assertEquals(2,values.size());
assertEquals("1",values.get(0));
assertEquals("2",values.get(1));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetCookiesWithAttributes() throws Exception {
Message m=new MessageImpl();
m.setExchange(new ExchangeImpl());
MetadataMap headers=createHeaders();
headers.putSingle(HttpHeaders.COOKIE,"$Version=1;a=b, $Version=1;c=d");
m.put(Message.PROTOCOL_HEADERS,headers);
HttpHeaders h=new HttpHeadersImpl(m);
Map cookies=h.getCookies();
assertEquals(2,cookies.size());
Cookie cookieA=cookies.get("a");
assertEquals("b",cookieA.getValue());
assertEquals(1,cookieA.getVersion());
Cookie cookieC=cookies.get("c");
assertEquals("d",cookieC.getValue());
assertEquals(1,cookieA.getVersion());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetContentTypeLowCase() throws Exception {
Message m=new MessageImpl();
Map> headers=new TreeMap>(String.CASE_INSENSITIVE_ORDER);
headers.put("content-type",Collections.singletonList("text/plain"));
m.put(Message.PROTOCOL_HEADERS,headers);
HttpHeaders h=new HttpHeadersImpl(m);
assertEquals("text/plain",h.getRequestHeaders().getFirst("Content-Type"));
}
InternalCallVerifier EqualityVerifier
@Test public void testGetCookies() throws Exception {
Message m=new MessageImpl();
m.setExchange(new ExchangeImpl());
MetadataMap headers=createHeaders();
headers.putSingle(HttpHeaders.COOKIE,"a=$b;c=d");
m.put(Message.PROTOCOL_HEADERS,headers);
HttpHeaders h=new HttpHeadersImpl(m);
Map cookies=h.getCookies();
assertEquals(2,cookies.size());
assertEquals("$b",cookies.get("a").getValue());
assertEquals("d",cookies.get("c").getValue());
}
InternalCallVerifier NullVerifier
@Test public void testNoRequestHeader() throws Exception {
Message m=control.createMock(Message.class);
m.get(Message.PROTOCOL_HEADERS);
MetadataMap headers=createHeader("COMPLEX_HEADER","b=c; param=c, a=b;param=b");
EasyMock.expectLastCall().andReturn(headers);
m.getContextualProperty("org.apache.cxf.http.header.split");
EasyMock.expectLastCall().andReturn("true");
control.replay();
HttpHeaders h=new HttpHeadersImpl(m);
List values=h.getRequestHeader("HEADER");
assertNull(values);
}
InternalCallVerifier EqualityVerifier
@Test public void testMediaType() throws Exception {
Message m=control.createMock(Message.class);
m.get(Message.PROTOCOL_HEADERS);
EasyMock.expectLastCall().andReturn(createHeaders());
control.replay();
HttpHeaders h=new HttpHeadersImpl(m);
assertEquals(MediaType.valueOf("*/*"),h.getMediaType());
}
InternalCallVerifier EqualityVerifier
@Test public void testMultipleAcceptableLanguages() throws Exception {
Message m=control.createMock(Message.class);
m.get(Message.PROTOCOL_HEADERS);
MetadataMap headers=createHeader(HttpHeaders.ACCEPT_LANGUAGE,"en;q=0.7, en-gb;q=0.8, da, zh-Hans-SG;q=0.9");
EasyMock.expectLastCall().andReturn(headers);
control.replay();
HttpHeaders h=new HttpHeadersImpl(m);
List languages=h.getAcceptableLanguages();
assertEquals(4,languages.size());
assertEquals(new Locale("da"),languages.get(0));
assertEquals(new Locale("zh","Hans-SG"),languages.get(1));
assertEquals(new Locale("en","GB"),languages.get(2));
assertEquals(new Locale("en"),languages.get(3));
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetHeaderWithQuotes2() throws Exception {
Message m=control.createMock(Message.class);
m.getContextualProperty("org.apache.cxf.http.header.split");
EasyMock.expectLastCall().andReturn("true");
m.get(Message.PROTOCOL_HEADERS);
MetadataMap headers=createHeader("X-WSSE","UsernameToken Username=\"Foo\", Nonce=\"bar\"");
EasyMock.expectLastCall().andReturn(headers);
control.replay();
HttpHeaders h=new HttpHeadersImpl(m);
List values=h.getRequestHeader("X-WSSE");
assertNotNull(values);
assertEquals(3,values.size());
assertEquals("UsernameToken",values.get(0));
assertEquals("Username=\"Foo\"",values.get(1));
assertEquals("Nonce=\"bar\"",values.get(2));
}
InternalCallVerifier EqualityVerifier
@Test public void testGetHeaders() throws Exception {
Message m=control.createMock(Message.class);
m.get(Message.PROTOCOL_HEADERS);
EasyMock.expectLastCall().andReturn(createHeaders());
m.getContextualProperty("org.apache.cxf.http.header.split");
EasyMock.expectLastCall().andReturn("true").anyTimes();
control.replay();
HttpHeaders h=new HttpHeadersImpl(m);
MultivaluedMap hs=h.getRequestHeaders();
List acceptValues=hs.get("Accept");
assertEquals(3,acceptValues.size());
assertEquals("text/bar;q=0.6",acceptValues.get(0));
assertEquals("text/*;q=1",acceptValues.get(1));
assertEquals("application/xml",acceptValues.get(2));
assertEquals(hs.getFirst("Content-Type"),"*/*");
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetHeaderWithQuotes3() throws Exception {
Message m=control.createMock(Message.class);
m.getContextualProperty("org.apache.cxf.http.header.split");
EasyMock.expectLastCall().andReturn("true");
m.get(Message.PROTOCOL_HEADERS);
MetadataMap headers=createHeader("COMPLEX_HEADER","\"value with space\"");
EasyMock.expectLastCall().andReturn(headers);
control.replay();
HttpHeaders h=new HttpHeadersImpl(m);
List values=h.getRequestHeader("COMPLEX_HEADER");
assertNotNull(values);
assertEquals(1,values.size());
assertEquals("value with space",values.get(0));
}
InternalCallVerifier EqualityVerifier
@Test public void testGetLanguage() throws Exception {
Message m=control.createMock(Message.class);
m.get(Message.PROTOCOL_HEADERS);
MetadataMap headers=createHeaders();
headers.putSingle(HttpHeaders.CONTENT_LANGUAGE,"en-US");
EasyMock.expectLastCall().andReturn(headers);
control.replay();
HttpHeaders h=new HttpHeadersImpl(m);
assertEquals("en_US",h.getLanguage().toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetCookiesWithComma() throws Exception {
Message m=new MessageImpl();
Exchange ex=new ExchangeImpl();
ex.setInMessage(m);
ex.put("org.apache.cxf.http.cookie.separator",",");
m.setExchange(ex);
MetadataMap headers=createHeaders();
headers.putSingle(HttpHeaders.COOKIE,"a=b,c=d");
m.put(Message.PROTOCOL_HEADERS,headers);
HttpHeaders h=new HttpHeadersImpl(m);
Map cookies=h.getCookies();
assertEquals(2,cookies.size());
assertEquals("b",cookies.get("a").getValue());
assertEquals("d",cookies.get("c").getValue());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetMissingContentLength() throws Exception {
Message m=new MessageImpl();
m.put(Message.PROTOCOL_HEADERS,new MetadataMap());
HttpHeaders h=new HttpHeadersImpl(m);
assertEquals(-1,h.getLength());
}
UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testUnmodifiableRequestHeaders() throws Exception {
Message m=control.createMock(Message.class);
m.getContextualProperty("org.apache.cxf.http.header.split");
EasyMock.expectLastCall().andReturn("true").anyTimes();
m.get(Message.PROTOCOL_HEADERS);
MetadataMap headers=createHeader(HttpHeaders.ACCEPT_LANGUAGE,"en;q=0.7, en-gb;q=0.8, da");
EasyMock.expectLastCall().andReturn(headers);
control.replay();
HttpHeaders h=new HttpHeadersImpl(m);
List languages=h.getAcceptableLanguages();
assertEquals(3,languages.size());
languages.clear();
languages=h.getAcceptableLanguages();
assertEquals(3,languages.size());
MultivaluedMap rHeaders=h.getRequestHeaders();
List acceptL=rHeaders.get(HttpHeaders.ACCEPT_LANGUAGE);
assertEquals(3,acceptL.size());
try {
rHeaders.clear();
fail();
}
catch ( UnsupportedOperationException ex) {
}
}
InternalCallVerifier NullVerifier
@Test public void testGetNullLanguage() throws Exception {
Message m=control.createMock(Message.class);
m.get(Message.PROTOCOL_HEADERS);
EasyMock.expectLastCall().andReturn(createHeaders());
control.replay();
HttpHeaders h=new HttpHeadersImpl(m);
assertNull(h.getLanguage());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetCookieWithAttributes() throws Exception {
Message m=new MessageImpl();
m.setExchange(new ExchangeImpl());
MetadataMap headers=createHeaders();
headers.putSingle(HttpHeaders.COOKIE,"$Version=1;a=b");
m.put(Message.PROTOCOL_HEADERS,headers);
HttpHeaders h=new HttpHeadersImpl(m);
Map cookies=h.getCookies();
assertEquals(1,cookies.size());
Cookie cookie=cookies.get("a");
assertEquals("b",cookie.getValue());
assertEquals(1,cookie.getVersion());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetHeader() throws Exception {
Message m=control.createMock(Message.class);
m.getContextualProperty("org.apache.cxf.http.header.split");
EasyMock.expectLastCall().andReturn("true");
m.get(Message.PROTOCOL_HEADERS);
EasyMock.expectLastCall().andReturn(createHeaders());
control.replay();
HttpHeaders h=new HttpHeadersImpl(m);
List acceptValues=h.getRequestHeader("Accept");
assertEquals(3,acceptValues.size());
assertEquals("text/bar;q=0.6",acceptValues.get(0));
assertEquals("text/*;q=1",acceptValues.get(1));
assertEquals("application/xml",acceptValues.get(2));
List contentValues=h.getRequestHeader("Content-Type");
assertEquals(1,contentValues.size());
assertEquals("*/*",contentValues.get(0));
List dateValues=h.getRequestHeader("Date");
assertEquals(1,dateValues.size());
assertEquals("Tue, 21 Oct 2008 17:00:00 GMT",dateValues.get(0));
}
InternalCallVerifier EqualityVerifier
@Test public void testGetHeaderString() throws Exception {
Message m=new MessageImpl();
m.put(Message.PROTOCOL_HEADERS,createHeaders());
HttpHeaders h=new HttpHeadersImpl(m);
String date=h.getHeaderString("Date");
assertEquals("Tue, 21 Oct 2008 17:00:00 GMT",date);
}
InternalCallVerifier EqualityVerifier
@Test public void testGetMediaTypes() throws Exception {
Message m=control.createMock(Message.class);
m.get(Message.PROTOCOL_HEADERS);
EasyMock.expectLastCall().andReturn(createHeaders());
control.replay();
HttpHeaders h=new HttpHeadersImpl(m);
List acceptValues=h.getAcceptableMediaTypes();
assertEquals(3,acceptValues.size());
assertEquals("text/*;q=1",acceptValues.get(0).toString());
assertEquals("application/xml",acceptValues.get(1).toString());
assertEquals("text/bar;q=0.6",acceptValues.get(2).toString());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetDate() throws Exception {
Message m=new MessageImpl();
m.put(Message.PROTOCOL_HEADERS,createHeaders());
HttpHeaders h=new HttpHeadersImpl(m);
List dateValues=h.getRequestHeader("Date");
assertEquals(1,dateValues.size());
assertEquals("Tue, 21 Oct 2008 17:00:00 GMT",dateValues.get(0));
Date d=h.getDate();
String theDateValue=HttpUtils.getHttpDateFormat().format(d);
assertEquals(theDateValue,"Tue, 21 Oct 2008 17:00:00 GMT");
}
InternalCallVerifier EqualityVerifier
@Test public void testGetContentLength() throws Exception {
Message m=new MessageImpl();
m.put(Message.PROTOCOL_HEADERS,createHeaders());
HttpHeaders h=new HttpHeadersImpl(m);
assertEquals(10,h.getLength());
}
Class: org.apache.cxf.jaxrs.impl.LinkBuilderImplTest InternalCallVerifier EqualityVerifier
@Test public void testBuildManyRels() throws Exception {
Link.Builder linkBuilder=new LinkBuilderImpl();
Link prevLink=linkBuilder.uri("http://example.com/page1").rel("1").rel("2").build();
assertEquals(";rel=\"1 2\"",prevLink.toString());
}
BooleanVerifier InternalCallVerifier
@Test public void testCreateFromMethod() throws Exception {
Link.Builder linkBuilder=Link.fromMethod(TestResource.class,"consumesAppJson");
Link link=linkBuilder.build();
String resource=link.toString();
assertTrue(resource.contains(""));
}
InternalCallVerifier EqualityVerifier
@Test public void testSeveralAttributes() throws Exception {
Link.Builder linkBuilder=new LinkBuilderImpl();
Link prevLink=linkBuilder.uri("http://example.com/page1").rel("previous").title("A title").build();
assertEquals(";rel=\"previous\";title=\"A title\"",prevLink.toString());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBuildObjects() throws Exception {
StringBuilder path1=new StringBuilder().append("p1");
ByteArrayInputStream path2=new ByteArrayInputStream("p2".getBytes()){
@Override public String toString(){
return "p2";
}
}
;
URI path3=new URI("p3");
String expected="<" + "http://host.com:888/" + "p1/p2/p3"+ ">";
Link.Builder builder=Link.fromUri("http://host.com:888/" + "{x1}/{x2}/{x3}");
Link link=builder.build(path1,path2,path3);
assertNotNull(link);
assertEquals(link.toString(),expected);
}
InternalCallVerifier EqualityVerifier
@Test public void testBuild() throws Exception {
Link.Builder linkBuilder=new LinkBuilderImpl();
Link prevLink=linkBuilder.uri("http://example.com/page1").rel("previous").build();
assertEquals(";rel=\"previous\"",prevLink.toString());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testBuildRelativized() throws Exception {
Link.Builder linkBuilder=new LinkBuilderImpl();
URI base=URI.create("http://example.com/page2");
Link prevLink=linkBuilder.uri("http://example.com/page1").rel("previous").buildRelativized(base);
assertEquals(";rel=\"previous\"",prevLink.toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testRelativeLink2() throws Exception {
Link.Builder linkBuilder=Link.fromUri("/relative");
linkBuilder.baseUri("http://localhost:8080/base/path");
Link link=linkBuilder.rel("next").build();
assertEquals(";rel=\"next\"",link.toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testRelativeLink() throws Exception {
Link.Builder linkBuilder=Link.fromUri("relative");
linkBuilder.baseUri("http://localhost:8080/base/path");
Link link=linkBuilder.rel("next").build();
assertEquals(";rel=\"next\"",link.toString());
}
Class: org.apache.cxf.jaxrs.impl.LinkHeaderProviderTest InternalCallVerifier EqualityVerifier
@Test public void testFromComplexString(){
Link l=Link.valueOf(";rel=next;title=\"Next Link\";type=text/xml;method=get");
assertEquals("http://bar",l.getUri().toString());
String rel=l.getRel();
assertEquals("next",rel);
assertEquals("Next Link",l.getTitle());
assertEquals("text/xml",l.getType());
assertEquals("get",l.getParams().get("method"));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testToString(){
String headerValue=";rel=next;title=\"Next Link\";type=text/xml;method=get";
String expected=";rel=\"next\";title=\"Next Link\";type=\"text/xml\";method=\"get\"";
Link l=Link.valueOf(headerValue);
String result=l.toString();
assertEquals(expected,result);
}
Class: org.apache.cxf.jaxrs.impl.MediaTypeHeaderProviderTest InternalCallVerifier EqualityVerifier
@Test public void testTypeWithExtendedParameters(){
MediaType mt=MediaType.valueOf("multipart/related;type=application/dicom+xml");
assertEquals("multipart",mt.getType());
assertEquals("related",mt.getSubtype());
Map params2=mt.getParameters();
assertEquals(1,params2.size());
assertEquals("application/dicom+xml",params2.get("type"));
}
InternalCallVerifier EqualityVerifier
@Test public void testTypeWithExtendedParametersQuote(){
MediaType mt=MediaType.valueOf("multipart/related;type=\"application/dicom+xml\"");
assertEquals("multipart",mt.getType());
assertEquals("related",mt.getSubtype());
Map params2=mt.getParameters();
assertEquals(1,params2.size());
assertEquals("\"application/dicom+xml\"",params2.get("type"));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testHeaderFileName(){
String fileName="version_2006(3).pdf";
String header="application/octet-stream; name=\"%s\"";
String value=String.format(header,fileName);
MediaTypeHeaderProvider provider=new MediaTypeHeaderProvider();
MediaType mt=provider.fromString(value);
assertEquals("application",mt.getType());
assertEquals("octet-stream",mt.getSubtype());
Map params=mt.getParameters();
assertEquals(1,params.size());
assertEquals("\"version_2006(3).pdf\"",params.get("name"));
}
InternalCallVerifier EqualityVerifier
@Test public void testTypeWithExtendedAndBoundaryParameter(){
MediaType mt=MediaType.valueOf("multipart/related; type=application/dicom+xml; boundary=\"uuid:b9aecb2a-ab37-48d6-a1cd-b2f4f7fa63cb\"");
assertEquals("multipart",mt.getType());
assertEquals("related",mt.getSubtype());
Map params2=mt.getParameters();
assertEquals(2,params2.size());
assertEquals("\"uuid:b9aecb2a-ab37-48d6-a1cd-b2f4f7fa63cb\"",params2.get("boundary"));
assertEquals("application/dicom+xml",params2.get("type"));
}
InternalCallVerifier EqualityVerifier
@Test public void testTypeWithParameters(){
MediaType mt=MediaType.valueOf("text/html;q=1234;b=4321");
assertEquals("text",mt.getType());
assertEquals("html",mt.getSubtype());
Map params2=mt.getParameters();
assertEquals(2,params2.size());
assertEquals("1234",params2.get("q"));
assertEquals("4321",params2.get("b"));
}
Class: org.apache.cxf.jaxrs.impl.MetadataMapTest InternalCallVerifier EqualityVerifier
@Test public void testPutSingleNullKeyCaseSensitive(){
MetadataMap m=new MetadataMap(false,true);
m.putSingle(null,"null");
m.putSingle(null,"null2");
assertEquals(1,m.get(null).size());
assertEquals("null2",m.getFirst(null));
}
InternalCallVerifier EqualityVerifier
@Test public void testCopyAndUpdate(){
MetadataMap m=new MetadataMap();
m.add("baz","bar");
MetadataMap m2=new MetadataMap(m);
m.remove("baz");
m.add("baz","foo");
assertEquals("bar",m2.getFirst("baz"));
assertEquals("foo",m.getFirst("baz"));
}
BooleanVerifier InternalCallVerifier
@Test public void testContainsKeyCaseInsensitive(){
MetadataMap m=new MetadataMap(false,true);
m.putSingle("a","b");
assertTrue(m.containsKey("a"));
assertTrue(m.containsKey("A"));
}
BooleanVerifier InternalCallVerifier
@Test public void testContainsKeyCaseSensitive(){
MetadataMap m=new MetadataMap();
m.putSingle("a","b");
assertTrue(m.containsKey("a"));
assertFalse(m.containsKey("A"));
}
InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testPutSingleNullKeyCaseSensitive2(){
MetadataMap map=new MetadataMap(false,true);
Object obj1=new Object();
Object obj2=new Object();
map.putSingle("key",obj1);
map.putSingle("key",obj2);
map.putSingle(null,obj2);
map.putSingle(null,obj1);
assertEquals(2,map.size());
assertEquals(1,map.get(null).size());
assertSame(map.getFirst("key"),obj2);
assertSame(map.getFirst(null),obj1);
}
InternalCallVerifier EqualityVerifier
@Test public void testRemoveCaseInsensitive(){
MetadataMap m=new MetadataMap(false,true);
List value1=new ArrayList();
value1.add("bar");
value1.add("foo");
m.put("baz",value1);
m.putSingle("baz","clazz");
assertEquals(1,m.size());
m.remove("Baz");
assertEquals(0,m.size());
}
InternalCallVerifier EqualityVerifier
@Test public void testAddAndGetFirst(){
MetadataMap m=new MetadataMap();
m.add("baz","bar");
List value=m.get("baz");
assertEquals("Only a single value should be in the list",1,value.size());
assertEquals("Value is wrong","bar",value.get(0));
m.add("baz","foo");
value=m.get("baz");
assertEquals("Two values should be in the list",2,value.size());
assertEquals("Value1 is wrong","bar",value.get(0));
assertEquals("Value2 is wrong","foo",value.get(1));
assertEquals("GetFirst value is wrong","bar",m.getFirst("baz"));
}
InternalCallVerifier EqualityVerifier
@Test public void testAddFirst(){
MetadataMap m=new MetadataMap();
m.addFirst("baz","foo");
List values=m.get("baz");
assertEquals(1,values.size());
assertEquals("foo",values.get(0));
m.addFirst("baz","clazz");
values=m.get("baz");
assertEquals(2,values.size());
assertEquals("clazz",values.get(0));
assertEquals("foo",values.get(1));
}
InternalCallVerifier NullVerifier
@Test public void testGetFirstEmptyMap(){
MetadataMap m=new MetadataMap();
assertNull(m.getFirst("key"));
m.add("key","1");
m.get("key").clear();
assertNull(m.getFirst("key"));
}
InternalCallVerifier EqualityVerifier
@Test public void testAddFirstUnmodifiableListFirst(){
MetadataMap m=new MetadataMap();
m.put("baz",Arrays.asList("foo"));
List values=m.get("baz");
assertEquals(1,values.size());
assertEquals("foo",values.get(0));
m.addFirst("baz","clazz");
values=m.get("baz");
assertEquals(2,values.size());
assertEquals("clazz",values.get(0));
assertEquals("foo",values.get(1));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testCompareIgnoreValueOrder(){
MetadataMap m=new MetadataMap();
m.add("baz","bar1");
m.add("baz","bar2");
List values=m.get("baz");
assertEquals("bar1",values.get(0));
assertEquals("bar2",values.get(1));
MetadataMap m2=new MetadataMap();
m2.add("baz","bar2");
m2.add("baz","bar1");
values=m2.get("baz");
assertEquals("bar2",values.get(0));
assertEquals("bar1",values.get(1));
assertTrue(m.equalsIgnoreValueOrder(m2));
assertTrue(m.equalsIgnoreValueOrder(m));
assertTrue(m2.equalsIgnoreValueOrder(m));
MetadataMap m3=new MetadataMap();
m3.add("baz","bar1");
assertFalse(m.equalsIgnoreValueOrder(m3));
assertFalse(m2.equalsIgnoreValueOrder(m3));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testPutSingleCaseInsensitive(){
MetadataMap m=new MetadataMap(false,true);
List value1=new ArrayList();
value1.add("bar");
value1.add("foo");
m.put("baz",value1);
m.putSingle("baz","clazz");
assertEquals(1,m.size());
List value2=m.get("baz");
assertEquals("Only a single value should be in the list",1,value2.size());
assertEquals("Value is wrong","clazz",value2.get(0));
m.putSingle("Baz","clazz2");
assertEquals(1,m.size());
value2=m.get("baz");
assertEquals("Only a single value should be in the list",1,value2.size());
assertEquals("Value is wrong","clazz2",value2.get(0));
assertTrue(m.containsKey("Baz"));
assertTrue(m.containsKey("baz"));
}
InternalCallVerifier EqualityVerifier
@Test public void testPutAllCaseInsensitive(){
MetadataMap m=new MetadataMap(false,true);
List value1=new ArrayList();
value1.add("bar");
value1.add("foo");
m.put("baz",value1);
assertEquals(1,m.size());
List values=m.get("baz");
assertEquals(2,values.size());
assertEquals("bar",values.get(0));
assertEquals("foo",values.get(1));
MetadataMap m2=new MetadataMap(false,true);
List value2=new ArrayList();
value2.add("bar2");
value2.add("foo2");
m2.put("BaZ",value2);
m.putAll(m2);
assertEquals(1,m.size());
values=m.get("Baz");
assertEquals(2,values.size());
assertEquals("bar2",values.get(0));
assertEquals("foo2",values.get(1));
}
BooleanVerifier InternalCallVerifier
@Test public void testKeySetCaseSensitive(){
MetadataMap m=new MetadataMap();
m.putSingle("a","b");
assertTrue(m.keySet().contains("a"));
assertFalse(m.keySet().contains("A"));
}
InternalCallVerifier EqualityVerifier
@Test public void testAddAll(){
MetadataMap m=new MetadataMap();
List values=new ArrayList();
values.add("foo");
m.addAll("baz",values);
values=m.get("baz");
assertEquals(1,values.size());
assertEquals("foo",values.get(0));
m.addAll("baz",Collections.singletonList("foo2"));
values=m.get("baz");
assertEquals(2,values.size());
assertEquals("foo",values.get(0));
assertEquals("foo2",values.get(1));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testGetCaseInsensitive(){
MetadataMap m=new MetadataMap();
m.add("Baz","bar");
MetadataMap m2=new MetadataMap(m,true,true);
assertEquals("bar",m2.getFirst("baZ"));
assertEquals("bar",m2.getFirst("Baz"));
assertTrue(m2.containsKey("BaZ"));
assertTrue(m2.containsKey("Baz"));
List values=m2.get("baz");
assertEquals(1,values.size());
assertEquals("bar",values.get(0).toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testPutSingleNullKey(){
MetadataMap m=new MetadataMap();
m.putSingle(null,"null");
m.putSingle(null,"null2");
assertEquals(1,m.get(null).size());
assertEquals("null2",m.getFirst(null));
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testPutSingle(){
MetadataMap m=new MetadataMap();
List value1=new ArrayList();
value1.add("bar");
value1.add("foo");
m.put("baz",value1);
m.putSingle("baz","clazz");
List value2=m.get("baz");
assertEquals("Only a single value should be in the list",1,value2.size());
assertEquals("Value is wrong","clazz",value2.get(0));
assertNull(m.get("baZ"));
}
BooleanVerifier InternalCallVerifier
@Test public void testKeySetCaseInsensitive(){
MetadataMap m=new MetadataMap(false,true);
m.putSingle("a","b");
assertTrue(m.keySet().contains("a"));
assertTrue(m.keySet().contains("A"));
}
Class: org.apache.cxf.jaxrs.impl.NewCookieHeaderProviderTest BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testFromComplexStringWithExpiresAndHttpOnly(){
NewCookie c=NewCookie.valueOf("foo=bar;Comment=comment;Path=path;Max-Age=10;Domain=domain;Secure;" + "Expires=Wed, 09 Jun 2021 10:18:14 GMT;HttpOnly;Version=1");
assertTrue("bar".equals(c.getValue()) && "foo".equals(c.getName()));
assertTrue(1 == c.getVersion() && "path".equals(c.getPath()) && "domain".equals(c.getDomain()) && "comment".equals(c.getComment()) && c.isSecure() && c.isHttpOnly() && 10 == c.getMaxAge());
Date d=c.getExpiry();
assertNotNull(d);
assertEquals("Wed, 09 Jun 2021 10:18:14 GMT",HttpUtils.toHttpDate(d));
}
Class: org.apache.cxf.jaxrs.impl.PathSegmentImplTest InternalCallVerifier EqualityVerifier
@Test public void testPlainPathSegment(){
PathSegment ps=new PathSegmentImpl("bar");
assertEquals("bar",ps.getPath());
assertEquals(0,ps.getMatrixParameters().size());
}
InternalCallVerifier EqualityVerifier
@Test public void testPathSegmentWithDecodedMatrixParams(){
PathSegment ps=new PathSegmentImpl("bar%20foo;a=1%202");
assertEquals("bar foo",ps.getPath());
MultivaluedMap params=ps.getMatrixParameters();
assertEquals(1,params.size());
assertEquals(1,params.get("a").size());
assertEquals("1 2",params.get("a").get(0));
}
InternalCallVerifier EqualityVerifier
@Test public void testPathSegmentWithMatrixParams(){
PathSegment ps=new PathSegmentImpl("bar;a=1;a=2;b=3%202",false);
assertEquals("bar",ps.getPath());
MultivaluedMap params=ps.getMatrixParameters();
assertEquals(2,params.size());
assertEquals(2,params.get("a").size());
assertEquals("1",params.get("a").get(0));
assertEquals("2",params.get("a").get(1));
assertEquals("3%202",params.getFirst("b"));
}
Class: org.apache.cxf.jaxrs.impl.RequestImplTest InternalCallVerifier NullVerifier
@Test public void testIfNoneMatchAndDateWithNonMatchingTags() throws Exception {
metadata.putSingle(HttpHeaders.IF_NONE_MATCH,"\"123\"");
metadata.putSingle("If-Modified-Since","Tue, 20 Oct 2008 14:00:00 GMT");
Date lastModified=new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz",Locale.ENGLISH).parse("Mon, 21 Oct 2008 14:00:00 GMT");
ResponseBuilder rb=new RequestImpl(m).evaluatePreconditions(lastModified,new EntityTag("124"));
assertNull("Dates must not be checked if tags do not match",rb);
}
InternalCallVerifier NullVerifier
@Test public void testBeforeDate() throws Exception {
metadata.putSingle("If-Modified-Since","Tue, 21 Oct 2008 14:00:00 GMT");
Date serverDate=new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz",Locale.ENGLISH).parse("Tue, 21 Oct 2008 17:00:00 GMT");
ResponseBuilder rb=new RequestImpl(m).evaluatePreconditions(serverDate);
assertNull("Precondition must be met",rb);
}
InternalCallVerifier NullVerifier
@Test public void testIfNoneMatchAndDateWithMatchingTags() throws Exception {
metadata.putSingle(HttpHeaders.IF_NONE_MATCH,"\"123\"");
metadata.putSingle("If-Modified-Since","Tue, 21 Oct 2008 14:00:00 GMT");
Date lastModified=new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz",Locale.ENGLISH).parse("Mon, 22 Oct 2008 14:00:00 GMT");
ResponseBuilder rb=new RequestImpl(m).evaluatePreconditions(lastModified,new EntityTag("\"123\""));
assertNull("Precondition is not met",rb);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testAfterDate() throws Exception {
metadata.putSingle("If-Modified-Since","Tue, 21 Oct 2008 14:00:00 GMT");
Date lastModified=new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz",Locale.ENGLISH).parse("Mon, 20 Oct 2008 14:00:00 GMT");
ResponseBuilder rb=new RequestImpl(m).evaluatePreconditions(lastModified);
assertNotNull("Precondition is not met",rb);
Response r=rb.build();
assertEquals("If-Modified-Since precondition was not met",304,r.getStatus());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testWeakEtags(){
metadata.putSingle("If-Match",new EntityTag("123",true).toString());
ResponseBuilder rb=new RequestImpl(m).evaluatePreconditions(new EntityTag("123"));
assertNotNull("Strict compararison is required",rb);
Response r=rb.build();
assertEquals("If-Match precondition was not met",412,r.getStatus());
assertEquals("Response should include ETag","\"123\"",r.getMetadata().getFirst("ETag").toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testBeforeDateIfNotModified() throws Exception {
metadata.putSingle(HttpHeaders.IF_UNMODIFIED_SINCE,"Mon, 20 Oct 2008 14:00:00 GMT");
Date serverDate=new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz",Locale.ENGLISH).parse("Tue, 21 Oct 2008 14:00:00 GMT");
ResponseBuilder rb=new RequestImpl(m).evaluatePreconditions(serverDate);
assertEquals("Precondition must not be met",412,rb.build().getStatus());
}
InternalCallVerifier EqualityVerifier
@Test public void testStarEtagsIfNotMatchPut(){
metadata.putSingle(HttpHeaders.IF_NONE_MATCH,"*");
m.put(Message.HTTP_REQUEST_METHOD,"PUT");
ResponseBuilder rb=new RequestImpl(m).evaluatePreconditions(new EntityTag("123"));
assertEquals("Precondition must not be met",412,rb.build().getStatus());
}
Class: org.apache.cxf.jaxrs.impl.RequestPreprocessorTest InternalCallVerifier EqualityVerifier
@Test public void testTypeQuery(){
Message m=mockMessage("http://localhost:8080","/bar","_type=xml","POST");
RequestPreprocessor sqh=new RequestPreprocessor();
sqh.preprocess(m,new UriInfoImpl(m,null));
assertEquals("POST",m.get(Message.HTTP_REQUEST_METHOD));
assertEquals("application/xml",m.get(Message.ACCEPT_CONTENT_TYPE));
}
Class: org.apache.cxf.jaxrs.impl.ResponseBuilderImplTest InternalCallVerifier EqualityVerifier
@Test public void testEntityTag(){
Response r=Response.ok().tag(new EntityTag("foo")).build();
String eTag=r.getMetadata().getFirst("ETag").toString();
assertEquals("\"foo\"",eTag);
}
InternalCallVerifier EqualityVerifier
@Test public void testTagStringWithQuotes(){
Response r=Response.ok().tag("\"foo\"").build();
String eTag=r.getMetadata().getFirst("ETag").toString();
assertEquals("\"foo\"",eTag);
}
InternalCallVerifier EqualityVerifier
@Test public void testTagString(){
Response r=Response.ok().tag("foo").build();
String eTag=r.getMetadata().getFirst("ETag").toString();
assertEquals("\"foo\"",eTag);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testVariant2() throws Exception {
List encoding=Arrays.asList("gzip","compress");
MediaType mt=MediaType.APPLICATION_JSON_TYPE;
ResponseBuilder rb=Response.ok();
rb=rb.variants(getVariantList(encoding,mt).toArray(new Variant[0]));
Response response=rb.build();
List enc=response.getHeaders().get(HttpHeaders.CONTENT_ENCODING);
assertTrue(encoding.containsAll(enc));
List ct=response.getHeaders().get(HttpHeaders.CONTENT_TYPE);
assertTrue(ct.contains(mt));
}
InternalCallVerifier EqualityVerifier
@Test public void testEntityTag2(){
Response r=Response.ok().tag(new EntityTag("\"foo\"")).build();
String eTag=r.getMetadata().getFirst("ETag").toString();
assertEquals("\"foo\"",eTag);
}
Class: org.apache.cxf.jaxrs.impl.ResponseImplTest InternalCallVerifier NullVerifier
@Test public void testGetNoLinkBuilder() throws Exception {
Response response=Response.ok().build();
Builder builder=response.getLinkBuilder("anyrelation");
assertNull(builder);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testStatuInfoForOKStatus(){
StatusType si=new ResponseImpl(200,"").getStatusInfo();
assertNotNull(si);
assertEquals(200,si.getStatusCode());
assertEquals(Status.Family.SUCCESSFUL,si.getFamily());
assertEquals("OK",si.getReasonPhrase());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testStatuInfoForClientErrorStatus(){
StatusType si=new ResponseImpl(400,"").getStatusInfo();
assertNotNull(si);
assertEquals(400,si.getStatusCode());
assertEquals(Status.Family.CLIENT_ERROR,si.getFamily());
assertEquals("Bad Request",si.getReasonPhrase());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testGetHeaderStringUsingHeaderDelegate() throws Exception {
StringBean bean=new StringBean("s3");
RuntimeDelegate original=RuntimeDelegate.getInstance();
RuntimeDelegate.setInstance(new StringBeanRuntimeDelegate(original));
try {
Response response=Response.ok().header(bean.get(),bean).build();
String header=response.getHeaderString(bean.get());
assertTrue(header.contains(bean.get()));
}
finally {
RuntimeDelegate.setInstance(original);
StringBeanRuntimeDelegate.assertNotStringBeanRuntimeDelegate();
}
}
InternalCallVerifier EqualityVerifier
@Test public void testGetMediaType(){
ResponseImpl ri=new ResponseImpl(200);
MetadataMap meta=new MetadataMap();
meta.add(HttpHeaders.CONTENT_TYPE,"text/xml");
ri.addMetadata(meta);
assertEquals("text/xml",ri.getMediaType().toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetLanguage(){
ResponseImpl ri=new ResponseImpl(200);
MetadataMap meta=new MetadataMap();
meta.add(HttpHeaders.CONTENT_LANGUAGE,"en-US");
ri.addMetadata(meta);
assertEquals("en_US",ri.getLanguage().toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testLocation(){
ResponseImpl ri=new ResponseImpl(200);
MetadataMap meta=new MetadataMap();
meta.add(HttpHeaders.LOCATION,"http://localhost:8080");
ri.addMetadata(meta);
assertEquals("http://localhost:8080",ri.getLocation().toString());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testStatuInfoForClientErrorStatus2(){
StatusType si=new ResponseImpl(499,"").getStatusInfo();
assertNotNull(si);
assertEquals(499,si.getStatusCode());
assertEquals(Status.Family.CLIENT_ERROR,si.getFamily());
assertEquals("",si.getReasonPhrase());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetCookies(){
ResponseImpl ri=new ResponseImpl(200);
MetadataMap meta=new MetadataMap();
meta.add("Set-Cookie",NewCookie.valueOf("a=b"));
meta.add("Set-Cookie",NewCookie.valueOf("c=d"));
ri.addMetadata(meta);
Map cookies=ri.getCookies();
assertEquals(2,cookies.size());
assertEquals("a=b;Version=1",cookies.get("a").toString());
assertEquals("c=d;Version=1",cookies.get("c").toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetContentLength(){
ResponseImpl ri=new ResponseImpl(200);
MetadataMap meta=new MetadataMap();
ri.addMetadata(meta);
assertEquals(-1,ri.getLength());
meta.add("Content-Length","10");
assertEquals(10,ri.getLength());
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testGetLinksNoRel(){
ResponseImpl ri=new ResponseImpl(200);
MetadataMap meta=new MetadataMap();
ri.addMetadata(meta);
Set links=ri.getLinks();
assertTrue(links.isEmpty());
meta.add(HttpHeaders.LINK,"");
meta.add(HttpHeaders.LINK,"");
assertFalse(ri.hasLink("next"));
Link next=ri.getLink("next");
assertNull(next);
assertFalse(ri.hasLink("prev"));
Link prev=ri.getLink("prev");
assertNull(prev);
links=ri.getLinks();
assertTrue(links.contains(Link.fromUri("http://next").build()));
assertTrue(links.contains(Link.fromUri("http://prev").build()));
}
InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testResourceImpl(){
String entity="bar";
ResponseImpl ri=new ResponseImpl(200,entity);
assertEquals("Wrong status",ri.getStatus(),200);
assertSame("Wrong entity",entity,ri.getEntity());
MetadataMap meta=new MetadataMap();
ri.addMetadata(meta);
ri.getMetadata();
assertSame("Wrong metadata",meta,ri.getMetadata());
assertSame("Wrong metadata",meta,ri.getHeaders());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetHeaderStrings(){
ResponseImpl ri=new ResponseImpl(200);
MetadataMap meta=new MetadataMap();
meta.add("Set-Cookie",NewCookie.valueOf("a=b"));
ri.addMetadata(meta);
MultivaluedMap headers=ri.getStringHeaders();
assertEquals(1,headers.size());
assertEquals("a=b;Version=1",headers.getFirst("Set-Cookie"));
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetHeaderString(){
ResponseImpl ri=new ResponseImpl(200);
MetadataMap meta=new MetadataMap();
ri.addMetadata(meta);
assertNull(ri.getHeaderString("a"));
meta.putSingle("a","aValue");
assertEquals("aValue",ri.getHeaderString("a"));
meta.add("a","aValue2");
assertEquals("aValue,aValue2",ri.getHeaderString("a"));
}
InternalCallVerifier EqualityVerifier
@Test public void testEntityTag(){
ResponseImpl ri=new ResponseImpl(200);
MetadataMap meta=new MetadataMap();
meta.add(HttpHeaders.ETAG,"1234");
ri.addMetadata(meta);
assertEquals("\"1234\"",ri.getEntityTag().toString());
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetLinks(){
ResponseImpl ri=new ResponseImpl(200);
MetadataMap meta=new MetadataMap();
ri.addMetadata(meta);
assertFalse(ri.hasLink("next"));
assertNull(ri.getLink("next"));
assertFalse(ri.hasLink("prev"));
assertNull(ri.getLink("prev"));
meta.add(HttpHeaders.LINK,";rel=next");
meta.add(HttpHeaders.LINK,";rel=prev");
assertTrue(ri.hasLink("next"));
Link next=ri.getLink("next");
assertNotNull(next);
assertTrue(ri.hasLink("prev"));
Link prev=ri.getLink("prev");
assertNotNull(prev);
Set links=ri.getLinks();
assertTrue(links.contains(next));
assertTrue(links.contains(prev));
assertEquals("http://localhost:8080/next;a=b",next.getUri().toString());
assertEquals("next",next.getRel());
assertEquals("http://prev",prev.getUri().toString());
assertEquals("prev",prev.getRel());
}
Class: org.apache.cxf.jaxrs.impl.SecurityContextImplTest InternalCallVerifier EqualityVerifier
@Test public void testAuthenticationScheme(){
Message m=new MessageImpl();
Map> requestHeaders=new TreeMap>(String.CASE_INSENSITIVE_ORDER);
List values=new ArrayList();
values.add("Digest realm=\"custom\"");
requestHeaders.put("Authorization",values);
m.put(Message.PROTOCOL_HEADERS,requestHeaders);
String scheme=new SecurityContextImpl(m).getAuthenticationScheme();
assertEquals("Digest",scheme);
}
Class: org.apache.cxf.jaxrs.impl.UriBuilderImplTest InternalCallVerifier EqualityVerifier
@Test public void testBuildWithNonEncodedSubstitutionValue6(){
UriBuilder ub=UriBuilder.fromPath("/");
URI uri=ub.path("%").build();
assertEquals("/%25",uri.toString());
uri=ub.replacePath("/%/{token}").build("{}");
assertEquals("/%25/%7B%7D",uri.toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testBuildWithNonEncodedSubstitutionValue7(){
UriBuilder ub=UriBuilder.fromPath("/");
URI uri=ub.replaceQueryParam("a","%").buildFromEncoded();
assertEquals("/?a=%25",uri.toString());
uri=ub.replaceQueryParam("a2","{token}").buildFromEncoded("{}");
assertEquals("/?a=%25&a2=%7B%7D",uri.toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testBuildWithNonEncodedSubstitutionValue8(){
UriBuilder ub=UriBuilder.fromPath("/");
URI uri=ub.replaceQueryParam("a","%").build();
assertEquals("/?a=%25",uri.toString());
uri=ub.replaceQueryParam("a2","{token}").build("{}");
assertEquals("/?a=%25&a2=%7B%7D",uri.toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testBuildFromEncodedMapMultipleTimes() throws Exception {
Map maps=new HashMap();
maps.put("x","x%yz");
maps.put("y","/path-absolute/test1");
maps.put("z","fred@example.com");
maps.put("w","path-rootless/test2");
Map maps1=new HashMap();
maps1.put("x","x%20yz");
maps1.put("y","/path-absolute/test1");
maps1.put("z","fred@example.com");
maps1.put("w","path-rootless/test2");
Map maps2=new HashMap();
maps2.put("x","x%yz");
maps2.put("y","/path-absolute/test1");
maps2.put("z","fred@example.com");
maps2.put("w","path-rootless/test2");
maps2.put("v","xyz");
String expectedPath="path-rootless/test2/x%25yz//path-absolute/test1/fred@example.com/x%25yz";
String expectedPath1="path-rootless/test2/x%20yz//path-absolute/test1/fred@example.com/x%20yz";
String expectedPath2="path-rootless/test2/x%25yz//path-absolute/test1/fred@example.com/x%25yz";
UriBuilder ub=UriBuilder.fromPath("").path("{w}/{x}/{y}/{z}/{x}");
URI uri=ub.buildFromEncodedMap(maps);
assertEquals(expectedPath,uri.getRawPath());
uri=ub.buildFromEncodedMap(maps1);
assertEquals(expectedPath1,uri.getRawPath());
uri=ub.buildFromEncodedMap(maps2);
assertEquals(expectedPath2,uri.getRawPath());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testAddPathMethod() throws Exception {
Method meth=BookStore.class.getMethod("updateBook",Book.class);
URI uri=new URI("http://foo/");
URI newUri=new UriBuilderImpl().uri(uri).path(meth).path("bar").build();
assertEquals("URI is not built correctly",new URI("http://foo/books/bar"),newUri);
}
InternalCallVerifier EqualityVerifier
@Test public void testResolveTemplatesMapBooleanSlashEncoded() throws Exception {
String expected="path-rootless%2Ftest2/x%25yz/%2Fpath-absolute%2F%2525test1/fred@example.com/x%25yz";
Map map=new HashMap();
map.put("x",new StringBuilder("x%yz"));
map.put("y",new StringBuffer("/path-absolute/%25test1"));
map.put("z",new Object(){
public String toString(){
return "fred@example.com";
}
}
);
map.put("w","path-rootless/test2");
UriBuilder builder=UriBuilder.fromPath("").path("{w}/{x}/{y}/{z}/{x}");
URI uri=builder.resolveTemplates(map,true).build();
assertEquals(expected,uri.getRawPath());
}
InternalCallVerifier EqualityVerifier
@Test public void testResolveTemplateFromMap2(){
String expected="path-rootless%2Ftest2/x%25yz/%2Fpath-absolute%2F%2525test1/fred@example.com/x%25yz";
Map map=new HashMap();
map.put("x",new StringBuilder("x%yz"));
map.put("y",new StringBuffer("/path-absolute/%25test1"));
map.put("z",new Object(){
public String toString(){
return "fred@example.com";
}
}
);
map.put("w","path-rootless/test2");
UriBuilder builder=UriBuilder.fromPath("").path("{w}/{x}/{y}/{z}/{x}");
URI uri=builder.resolveTemplates(map).build();
assertEquals(expected,uri.getRawPath());
}
InternalCallVerifier EqualityVerifier
@Test public void testAddPath() throws Exception {
URI uri=new URI("http://foo/bar");
URI newUri=new UriBuilderImpl().uri(uri).path("baz").build();
assertEquals("URI is not built correctly",new URI("http://foo/bar/baz"),newUri);
newUri=new UriBuilderImpl().uri(uri).path("baz").path("1").path("2").build();
assertEquals("URI is not built correctly",new URI("http://foo/bar/baz/1/2"),newUri);
}
InternalCallVerifier EqualityVerifier
@Test public void testAddPathClassMethod() throws Exception {
URI uri=new URI("http://foo/");
URI newUri=new UriBuilderImpl().uri(uri).path(BookStore.class).path(BookStore.class,"updateBook").path("bar").build();
assertEquals("URI is not built correctly",new URI("http://foo/bookstore/books/bar"),newUri);
}
InternalCallVerifier EqualityVerifier
@Test public void testUriTemplate2() throws Exception {
UriBuilder builder=UriBuilder.fromUri("http://localhost/{a}/{b}");
URI uri=builder.build("1","2");
assertEquals("http://localhost/1/2",uri.toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testResolveTemplateFromEncodedMap(){
String expected="path-rootless%2Ftest2/x%25yz/%2Fpath-absolute%2F%2525test1/fred@example.com/x%25yz";
Map map=new HashMap();
map.put("v",new StringBuilder("path-rootless%2Ftest2"));
map.put("w",new StringBuilder("x%yz"));
map.put("x",new Object(){
public String toString(){
return "%2Fpath-absolute%2F%2525test1";
}
}
);
map.put("y","fred@example.com");
UriBuilder builder=UriBuilder.fromPath("").path("{v}/{w}/{x}/{y}/{w}");
builder=builder.resolveTemplatesFromEncoded(map);
URI uri=builder.build();
assertEquals(expected,uri.getRawPath());
}
InternalCallVerifier EqualityVerifier
@Test public void testUri() throws Exception {
URI uri=new URI("http://foo/bar/baz?query=1#fragment");
URI newUri=new UriBuilderImpl().uri(uri).build();
assertEquals("URI is not built correctly",uri,newUri);
}
InternalCallVerifier EqualityVerifier
@Test public void testAddPathSlashes() throws Exception {
URI uri=new URI("http://foo/");
URI newUri=new UriBuilderImpl().uri(uri).path("/bar").path("baz/").path("/blah/").build();
assertEquals("URI is not built correctly",new URI("http://foo/bar/baz/blah/"),newUri);
}
InternalCallVerifier EqualityVerifier
@Test public void testAddPathClass() throws Exception {
URI uri=new URI("http://foo/");
URI newUri=new UriBuilderImpl().uri(uri).path(BookStore.class).path("/").build();
assertEquals("URI is not built correctly",new URI("http://foo/bookstore/"),newUri);
}
InternalCallVerifier EqualityVerifier
@Test public void testResolveTemplatesMapBooleanSlashNotEncoded() throws Exception {
String expected="path-rootless/test2/x%25yz//path-absolute/test1/fred@example.com/x%25yz";
Map map=new HashMap();
map.put("x",new StringBuilder("x%yz"));
map.put("y",new StringBuffer("/path-absolute/test1"));
map.put("z",new Object(){
public String toString(){
return "fred@example.com";
}
}
);
map.put("w","path-rootless/test2");
UriBuilder builder=UriBuilder.fromPath("").path("{w}/{x}/{y}/{z}/{x}");
URI uri=builder.resolveTemplates(map,false).build();
assertEquals(expected,uri.getRawPath());
}
InternalCallVerifier EqualityVerifier
@Test public void testAddPathSlashes3() throws Exception {
URI uri=new URI("http://foo/");
URI newUri=new UriBuilderImpl().uri(uri).path("/bar/").path("").path("baz").build();
assertEquals("URI is not built correctly",new URI("http://foo/bar/baz"),newUri);
}
InternalCallVerifier EqualityVerifier
@Test public void testToTemplateAndResolved(){
Map templs=new HashMap();
templs.put("a","1");
templs.put("b","2");
String template=((UriBuilderImpl)UriBuilder.fromPath("/{a}/{b}").queryParam("c","{c}")).resolveTemplates(templs).toTemplate();
assertEquals("/1/2?c={c}",template);
}
InternalCallVerifier EqualityVerifier
@Test public void testBuildWithNonEncodedSubstitutionValue3(){
UriBuilder ub=UriBuilder.fromPath("/");
URI uri=ub.path("{a}").buildFromEncoded("%");
assertEquals("/%25",uri.toString());
uri=ub.path("{token}").buildFromEncoded("%","{}");
assertEquals("/%25/%7B%7D",uri.toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testAddPathSlashes2() throws Exception {
URI uri=new URI("http://foo/");
URI newUri=new UriBuilderImpl().uri(uri).path("/bar///baz").path("blah//").build();
assertEquals("URI is not built correctly",new URI("http://foo/bar/baz/blah/"),newUri);
}
InternalCallVerifier EqualityVerifier
@Test public void testBuildWithNonEncodedSubstitutionValue4(){
UriBuilder ub=UriBuilder.fromPath("/");
URI uri=ub.path("{a}").build("%");
assertEquals("/%25",uri.toString());
uri=ub.path("{token}").build("%","{}");
assertEquals("/%25/%7B%7D",uri.toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testUriTemplate() throws Exception {
UriBuilder builder=UriBuilder.fromUri("http://localhost:8080/{a}/{b}");
URI uri=builder.build("1","2");
assertEquals("http://localhost:8080/1/2",uri.toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testBuildWithNonEncodedSubstitutionValue5(){
UriBuilder ub=UriBuilder.fromUri("/%25");
URI uri=ub.build();
assertEquals("/%25",uri.toString());
uri=ub.replacePath("/%/{token}").build("{}");
assertEquals("/%25/%7B%7D",uri.toString());
}
Class: org.apache.cxf.jaxrs.impl.UriInfoImplTest InternalCallVerifier EqualityVerifier
@Test public void testGetCaseinsensitiveQueryParameters(){
UriInfoImpl u=new UriInfoImpl(mockMessage("http://localhost:8080/baz","/bar"),null);
assertEquals("unexpected queries",0,u.getQueryParameters().size());
Message m=mockMessage("http://localhost:8080/baz","/bar","N=1%202&n=3&b=2&a%2Eb=ab");
m.put("org.apache.cxf.http.case_insensitive_queries","true");
u=new UriInfoImpl(m,null);
MultivaluedMap qps=u.getQueryParameters();
assertEquals("Number of queiries is wrong",3,qps.size());
assertEquals("Wrong query value",qps.get("n").get(0),"1 2");
assertEquals("Wrong query value",qps.get("n").get(1),"3");
assertEquals("Wrong query value",qps.get("b").get(0),"2");
assertEquals("Wrong query value",qps.get("a.b").get(0),"ab");
}
InternalCallVerifier EqualityVerifier
@Test public void testRelativizeAlreadyRelative() throws Exception {
Message mockMessage=mockMessage("http://localhost:8080/app/root/","/soup/");
UriInfoImpl u=new UriInfoImpl(mockMessage,null);
assertEquals("http://localhost:8080/app/root/soup/",u.getRequestUri().toString());
URI x=URI.create("x/");
assertEquals("http://localhost:8080/app/root/x/",u.resolve(x).toString());
assertEquals("../x/",u.relativize(x).toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testRelativizeChild() throws Exception {
Message mockMessage=mockMessage("http://example.com/app/root/","/a/b/c/");
UriInfoImpl u=new UriInfoImpl(mockMessage,null);
assertEquals("http://example.com/app/root/a/b/c/",u.getRequestUri().toString());
URI absolute=URI.create("http://example.com/app/root/a/b/c/d/e");
assertEquals("d/e",u.relativize(absolute).toString());
URI relativeToBase=URI.create("a/b/c/d/e");
assertEquals("d/e",u.relativize(relativeToBase).toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testRelativizeGrandParent() throws Exception {
Message mockMessage=mockMessage("http://example.com/app/root/","/a/b/c/");
UriInfoImpl u=new UriInfoImpl(mockMessage,null);
assertEquals("http://example.com/app/root/a/b/c/",u.getRequestUri().toString());
URI absolute=URI.create("http://example.com/app/root/a/");
assertEquals("../../",u.relativize(absolute).toString());
URI relativeToBase=URI.create("a/");
assertEquals("../../",u.relativize(relativeToBase).toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetQueryParameters(){
UriInfoImpl u=new UriInfoImpl(mockMessage("http://localhost:8080/baz","/bar"),null);
assertEquals("unexpected queries",0,u.getQueryParameters().size());
u=new UriInfoImpl(mockMessage("http://localhost:8080/baz","/bar","n=1%202"),null);
MultivaluedMap qps=u.getQueryParameters(false);
assertEquals("Number of queries is wrong",1,qps.size());
assertEquals("Wrong query value",qps.getFirst("n"),"1%202");
u=new UriInfoImpl(mockMessage("http://localhost:8080/baz","/bar","N=0&n=1%202&n=3&b=2&a%2Eb=ab"),null);
qps=u.getQueryParameters();
assertEquals("Number of queiries is wrong",4,qps.size());
assertEquals("Wrong query value",qps.get("N").get(0),"0");
assertEquals("Wrong query value",qps.get("n").get(0),"1 2");
assertEquals("Wrong query value",qps.get("n").get(1),"3");
assertEquals("Wrong query value",qps.get("b").get(0),"2");
assertEquals("Wrong query value",qps.get("a.b").get(0),"ab");
}
InternalCallVerifier EqualityVerifier
@Test public void testRelativizeOutsideBase() throws Exception {
Message mockMessage=mockMessage("http://example.com/app/root/","/a/b/c/");
UriInfoImpl u=new UriInfoImpl(mockMessage,null);
assertEquals("http://example.com/app/root/a/b/c/",u.getRequestUri().toString());
URI absolute=URI.create("http://example.com/otherapp/fred.txt");
assertEquals("../../../../../otherapp/fred.txt",u.relativize(absolute).toString());
URI relativeToBase=URI.create("../../otherapp/fred.txt");
assertEquals("../../../../../otherapp/fred.txt",u.relativize(relativeToBase).toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testResolveNormalizeComplex() throws Exception {
UriInfoImpl u=new UriInfoImpl(mockMessage("http://localhost:8080/baz/1/2/3/",null),null);
assertEquals("Wrong base path","http://localhost:8080/baz/1/2/3/",u.getBaseUri().toString());
URI resolved=u.resolve(new URI("../../a"));
assertEquals("http://localhost:8080/baz/1/a",resolved.toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testRelativizeSibling() throws Exception {
Message mockMessage=mockMessage("http://example.com/app/root/","/a/b/c.html");
UriInfoImpl u=new UriInfoImpl(mockMessage,null);
assertEquals("http://example.com/app/root/a/b/c.html",u.getRequestUri().toString());
URI absolute=URI.create("http://example.com/app/root/a/b/c.pdf");
assertEquals("c.pdf",u.relativize(absolute).toString());
URI relativeToBase=URI.create("a/b/c.pdf");
assertEquals("c.pdf",u.relativize(relativeToBase).toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testRelativizeNoCommonPrefix() throws Exception {
Message mockMessage=mockMessage("http://localhost:8080/app/root/","/soup");
UriInfoImpl u=new UriInfoImpl(mockMessage,null);
assertEquals("http://localhost:8080/app/root/soup",u.getRequestUri().toString());
URI otherHost=URI.create("http://localhost:8081/app/root/x");
assertEquals(otherHost,u.resolve(otherHost));
assertEquals(otherHost,u.relativize(otherHost));
}
InternalCallVerifier EqualityVerifier
@Test public void testResolveNormalizeSimple(){
UriInfoImpl u=new UriInfoImpl(mockMessage("http://localhost:8080/baz",null),null);
assertEquals("Wrong base path","http://localhost:8080/baz",u.getBaseUri().toString());
URI resolved=u.resolve(URI.create("./a"));
assertEquals("http://localhost:8080/a",resolved.toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testResolve(){
UriInfoImpl u=new UriInfoImpl(mockMessage("http://localhost:8080/baz/",null),null);
assertEquals("Wrong base path","http://localhost:8080/baz/",u.getBaseUri().toString());
URI resolved=u.resolve(URI.create("a"));
assertEquals("http://localhost:8080/baz/a",resolved.toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetTemplateParameters(){
MultivaluedMap values=new MetadataMap();
new URITemplate("/bar").match("/baz",values);
UriInfoImpl u=new UriInfoImpl(mockMessage("http://localhost:8080/baz","/bar"),values);
assertEquals("unexpected templates",0,u.getPathParameters().size());
values.clear();
new URITemplate("/{id}").match("/bar%201",values);
u=new UriInfoImpl(mockMessage("http://localhost:8080/baz","/bar%201"),values);
MultivaluedMap tps=u.getPathParameters(false);
assertEquals("Number of templates is wrong",1,tps.size());
assertEquals("Wrong template value",tps.getFirst("id"),"bar%201");
values.clear();
new URITemplate("/{id}/{baz}").match("/1%202/bar",values);
u=new UriInfoImpl(mockMessage("http://localhost:8080/baz","/1%202/bar"),values);
tps=u.getPathParameters();
assertEquals("Number of templates is wrong",2,tps.size());
assertEquals("Wrong template value",tps.getFirst("id"),"1 2");
assertEquals("Wrong template value",tps.getFirst("baz"),"bar");
values.clear();
new URITemplate("/bar").match("/bar",values);
u=new UriInfoImpl(mockMessage("http://localhost:8080/baz","/bar"),values);
assertEquals("unexpected templates",0,u.getPathParameters().size());
}
InternalCallVerifier EqualityVerifier
@Test public void testRelativizeCousin() throws Exception {
Message mockMessage=mockMessage("http://example.com/app/root/","/a/b/c/");
UriInfoImpl u=new UriInfoImpl(mockMessage,null);
assertEquals("http://example.com/app/root/a/b/c/",u.getRequestUri().toString());
URI absolute=URI.create("http://example.com/app/root/a/b2/c2/");
assertEquals("../../b2/c2/",u.relativize(absolute).toString());
URI relativeToBase=URI.create("a/b2/c2/");
assertEquals("../../b2/c2/",u.relativize(relativeToBase).toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetEncodedPathSegments(){
UriInfoImpl u=new UriInfoImpl(mockMessage("http://localhost:8080","/bar/foo/x%2Fb"),null);
List segments=u.getPathSegments(false);
assertEquals(3,segments.size());
assertEquals("bar",segments.get(0).toString());
assertEquals("foo",segments.get(1).toString());
assertEquals("x%2Fb",segments.get(2).toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testRelativize(){
UriInfoImpl u=new UriInfoImpl(mockMessage("http://localhost:8080/app/root","/a/b/c"),null);
assertEquals("Wrong Request Uri","http://localhost:8080/app/root/a/b/c",u.getRequestUri().toString());
URI relativized=u.relativize(URI.create("http://localhost:8080/app/root/a/d/e"));
assertEquals("../d/e",relativized.toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetPathSegments(){
UriInfoImpl u=new UriInfoImpl(mockMessage("http://localhost:8080","/bar/foo/x%2Fb"),null);
List segments=u.getPathSegments();
assertEquals(3,segments.size());
assertEquals("bar",segments.get(0).toString());
assertEquals("foo",segments.get(1).toString());
assertEquals("x/b",segments.get(2).toString());
}
Class: org.apache.cxf.jaxrs.impl.VariantListBuilderImplTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testBuildEnc(){
VariantListBuilderImpl vb=new VariantListBuilderImpl();
List variants=vb.encodings("zip","identity").add().build();
assertEquals("2 variants need to be created",2,variants.size());
assertTrue(verifyVariant(variants,new Variant(null,(Locale)null,"zip")));
assertTrue(verifyVariant(variants,new Variant(null,(Locale)null,"identity")));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testBuildType(){
VariantListBuilderImpl vb=new VariantListBuilderImpl();
List variants=vb.mediaTypes(new MediaType("*","*"),new MediaType("text","xml")).add().build();
assertEquals("2 variants need to be created",2,variants.size());
assertTrue(verifyVariant(variants,new Variant(new MediaType("*","*"),(Locale)null,null)));
assertTrue(verifyVariant(variants,new Variant(new MediaType("text","xml"),(Locale)null,null)));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testBuildTypeAndLang(){
VariantListBuilderImpl vb=new VariantListBuilderImpl();
MediaType mt1=new MediaType("*","*");
MediaType mt2=new MediaType("text","xml");
List variants=vb.mediaTypes(mt1,mt2).languages(new Locale("en"),new Locale("fr")).add().build();
assertEquals("8 variants need to be created",4,variants.size());
assertTrue(verifyVariant(variants,new Variant(mt1,new Locale("en"),null)));
assertTrue(verifyVariant(variants,new Variant(mt1,new Locale("fr"),null)));
assertTrue(verifyVariant(variants,new Variant(mt2,new Locale("en"),null)));
assertTrue(verifyVariant(variants,new Variant(mt2,new Locale("fr"),null)));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testBuildLang(){
VariantListBuilderImpl vb=new VariantListBuilderImpl();
List variants=vb.languages(new Locale("en"),new Locale("fr")).add().build();
assertEquals("2 variants need to be created",2,variants.size());
assertTrue(verifyVariant(variants,new Variant(null,new Locale("en"),null)));
assertTrue(verifyVariant(variants,new Variant(null,new Locale("en"),null)));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testBuildTypeAndEnc(){
VariantListBuilderImpl vb=new VariantListBuilderImpl();
MediaType mt1=new MediaType("*","*");
MediaType mt2=new MediaType("text","xml");
List variants=vb.mediaTypes(mt1,mt2).encodings("zip","identity").add().build();
assertEquals("4 variants need to be created",4,variants.size());
assertTrue(verifyVariant(variants,new Variant(mt1,(Locale)null,"zip")));
assertTrue(verifyVariant(variants,new Variant(mt1,(Locale)null,"identity")));
assertTrue(verifyVariant(variants,new Variant(mt2,(Locale)null,"zip")));
assertTrue(verifyVariant(variants,new Variant(mt2,(Locale)null,"identity")));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testBuildLangAndEnc(){
VariantListBuilderImpl vb=new VariantListBuilderImpl();
List variants=vb.languages(new Locale("en"),new Locale("fr")).encodings("zip","identity").add().build();
assertEquals("4 variants need to be created",4,variants.size());
assertTrue(verifyVariant(variants,new Variant(null,new Locale("en"),"zip")));
assertTrue(verifyVariant(variants,new Variant(null,new Locale("en"),"identity")));
assertTrue(verifyVariant(variants,new Variant(null,new Locale("fr"),"zip")));
assertTrue(verifyVariant(variants,new Variant(null,new Locale("fr"),"identity")));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testBuildAll(){
VariantListBuilderImpl vb=new VariantListBuilderImpl();
MediaType mt1=new MediaType("*","*");
MediaType mt2=new MediaType("text","xml");
List variants=vb.mediaTypes(mt1,mt2).languages(new Locale("en"),new Locale("fr")).encodings("zip","identity").add().build();
assertEquals("8 variants need to be created",8,variants.size());
assertTrue(verifyVariant(variants,new Variant(mt1,new Locale("en"),"zip")));
assertTrue(verifyVariant(variants,new Variant(mt1,new Locale("en"),"identity")));
assertTrue(verifyVariant(variants,new Variant(mt1,new Locale("fr"),"zip")));
assertTrue(verifyVariant(variants,new Variant(mt1,new Locale("fr"),"identity")));
assertTrue(verifyVariant(variants,new Variant(mt2,new Locale("en"),"zip")));
assertTrue(verifyVariant(variants,new Variant(mt2,new Locale("en"),"identity")));
assertTrue(verifyVariant(variants,new Variant(mt2,new Locale("fr"),"zip")));
assertTrue(verifyVariant(variants,new Variant(mt2,new Locale("fr"),"identity")));
}
Class: org.apache.cxf.jaxrs.json.basic.JsonMapObjectReaderWriterTest InternalCallVerifier EqualityVerifier
@Test public void testReadMap() throws Exception {
String json="{\"a\":\"aValue\",\"b\":123,\"c\":[\"cValue\"]}";
Map map=new JsonMapObjectReaderWriter().fromJson(json);
assertEquals(3,map.size());
assertEquals("aValue",map.get("a"));
assertEquals(123L,map.get("b"));
assertEquals(Collections.singletonList("cValue"),map.get("c"));
}
InternalCallVerifier EqualityVerifier
@Test public void testWriteMap() throws Exception {
Map map=new LinkedHashMap();
map.put("a","aValue");
map.put("b",123);
map.put("c",Collections.singletonList("cValue"));
String json=new JsonMapObjectReaderWriter().toJson(map);
assertEquals("{\"a\":\"aValue\",\"b\":123,\"c\":[\"cValue\"]}",json);
}
Class: org.apache.cxf.jaxrs.lifecycle.PerRequestResourceProviderTest BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetInstance(){
PerRequestResourceProvider rp=new PerRequestResourceProvider(Customer.class);
Message message=createMessage();
message.put(Message.QUERY_STRING,"a=aValue");
Customer c=(Customer)rp.getInstance(message);
assertNotNull(c.getUriInfo());
assertEquals("aValue",c.getQueryParam());
assertTrue(c.isPostConstuctCalled());
rp.releaseInstance(message,c);
assertTrue(c.isPreDestroyCalled());
}
Class: org.apache.cxf.jaxrs.model.ClassResourceInfoTest InternalCallVerifier IdentityVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetSameSubresource(){
ClassResourceInfo c=new ClassResourceInfo(TestClass.class);
assertEquals("No subresources expected",0,c.getSubResources().size());
assertNull(c.findResource(TestClass.class,TestClass.class));
ClassResourceInfo c1=c.getSubResource(TestClass.class,TestClass.class);
assertNotNull(c1);
assertSame(c1,c.findResource(TestClass.class,TestClass.class));
assertSame(c1,c.getSubResource(TestClass.class,TestClass.class));
assertEquals("Single subresources expected",1,c.getSubResources().size());
}
InternalCallVerifier IdentityVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetSubresourceSubclass(){
ClassResourceInfo c=new ClassResourceInfo(TestClass.class);
assertEquals("No subresources expected",0,c.getSubResources().size());
assertNull(c.findResource(TestClass.class,TestClass1.class));
ClassResourceInfo c1=c.getSubResource(TestClass.class,TestClass1.class);
assertNotNull(c1);
assertSame(c1,c.findResource(TestClass.class,TestClass1.class));
assertNull(c.findResource(TestClass.class,TestClass2.class));
ClassResourceInfo c2=c.getSubResource(TestClass.class,TestClass2.class);
assertNotNull(c2);
assertSame(c2,c.findResource(TestClass.class,TestClass2.class));
assertSame(c2,c.getSubResource(TestClass.class,TestClass2.class));
assertNotSame(c1,c2);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSubresourceInheritProduces(){
ClassResourceInfo c=ResourceUtils.createClassResourceInfo(TestClass2.class,TestClass2.class,true,true);
assertEquals("test/bar",c.getProduceMime().get(0).toString());
ClassResourceInfo sub=c.getSubResource(TestClass2.class,TestClass3.class);
assertNotNull(sub);
assertEquals("test/bar",sub.getProduceMime().get(0).toString());
sub=c.getSubResource(TestClass2.class,TestClass2.class);
assertNotNull(sub);
assertEquals("test/bar",sub.getProduceMime().get(0).toString());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testNameBindings(){
Application app=new TestApplication();
JAXRSServerFactoryBean bean=ResourceUtils.createApplication(app,true,true);
ClassResourceInfo cri=bean.getServiceFactory().getClassResourceInfo().get(0);
Set names=cri.getNameBindings();
assertEquals(Collections.singleton(CustomNameBinding.class.getName()),names);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testAllowedMethods(){
ClassResourceInfo c=ResourceUtils.createClassResourceInfo(TestClass3.class,TestClass3.class,false,false);
Set methods=c.getAllowedMethods();
assertEquals(2,methods.size());
assertTrue(methods.contains("HEAD") && methods.contains("GET"));
}
InternalCallVerifier EqualityVerifier
@Test public void testSubresourceWithProduces(){
ClassResourceInfo parent=ResourceUtils.createClassResourceInfo(TestClass2.class,TestClass2.class,true,true);
ClassResourceInfo c=ResourceUtils.createClassResourceInfo(TestClassWithProduces.class,TestClassWithProduces.class,true,true);
c.setParent(parent);
assertEquals("test/foo",c.getProduceMime().get(0).toString());
}
Class: org.apache.cxf.jaxrs.model.OperationResourceInfoTest InternalCallVerifier EqualityVerifier
@Test public void testProduceTypes() throws Exception {
OperationResourceInfo ori1=new OperationResourceInfo(TestClass.class.getMethod("doIt",new Class[]{}),new ClassResourceInfo(TestClass.class));
List ctypes=ori1.getProduceTypes();
assertEquals("Single media type expected",1,ctypes.size());
assertEquals("Method produce type should be used","text/plain",ctypes.get(0).toString());
OperationResourceInfo ori2=new OperationResourceInfo(TestClass.class.getMethod("doThat",new Class[]{}),new ClassResourceInfo(TestClass.class));
ctypes=ori2.getProduceTypes();
assertEquals("Single media type expected",1,ctypes.size());
assertEquals("Class resource produce type should be used","text/xml",ctypes.get(0).toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testConsumeTypes() throws Exception {
OperationResourceInfo ori1=new OperationResourceInfo(TestClass.class.getMethod("doIt",new Class[]{}),new ClassResourceInfo(TestClass.class));
List ctypes=ori1.getConsumeTypes();
assertEquals("Single media type expected",1,ctypes.size());
assertEquals("Class resource consume type should be used","application/xml",ctypes.get(0).toString());
OperationResourceInfo ori2=new OperationResourceInfo(TestClass.class.getMethod("doThat",new Class[]{}),new ClassResourceInfo(TestClass.class));
ctypes=ori2.getConsumeTypes();
assertEquals("Single media type expected",1,ctypes.size());
assertEquals("Method consume type should be used","application/atom+xml",ctypes.get(0).toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testComparator1() throws Exception {
OperationResourceInfo ori1=new OperationResourceInfo(TestClass.class.getMethod("doIt",new Class[]{}),new ClassResourceInfo(TestClass.class));
ori1.setURITemplate(new URITemplate("/"));
OperationResourceInfo ori2=new OperationResourceInfo(TestClass.class.getMethod("doThat",new Class[]{}),new ClassResourceInfo(TestClass.class));
ori2.setURITemplate(new URITemplate("/"));
OperationResourceInfoComparator cmp=new OperationResourceInfoComparator(null,null);
int result=cmp.compare(ori1,ori2);
assertEquals(0,result);
}
InternalCallVerifier EqualityVerifier
@Test public void testComparator2() throws Exception {
Message m=createMessage();
OperationResourceInfo ori1=new OperationResourceInfo(TestClass.class.getMethod("doIt",new Class[]{}),new ClassResourceInfo(TestClass.class));
ori1.setURITemplate(new URITemplate("/"));
OperationResourceInfo ori2=new OperationResourceInfo(TestClass.class.getMethod("doThat",new Class[]{}),new ClassResourceInfo(TestClass.class));
ori2.setURITemplate(new URITemplate("/"));
OperationResourceInfoComparator cmp=new OperationResourceInfoComparator(m,"POST",false,MediaType.WILDCARD_TYPE,Collections.singletonList(MediaType.WILDCARD_TYPE));
int result=cmp.compare(ori1,ori2);
assertEquals(0,result);
}
Class: org.apache.cxf.jaxrs.model.URITemplateTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testBaseTail3(){
URITemplate uriTemplate=new URITemplate("/{base:base.+suffix}/{tail}");
MultivaluedMap values=new MetadataMap();
assertFalse(uriTemplate.match("/base/tails",values));
assertFalse(uriTemplate.match("/base1/tails",values));
assertTrue(uriTemplate.match("/base1suffix/tails",values));
assertEquals("base1suffix",values.getFirst("base"));
assertEquals("tails",values.getFirst("tail"));
}
InternalCallVerifier EqualityVerifier
@Test public void testVariables(){
URITemplate ut=new URITemplate("/foo/{a}/bar{c:\\d}{b:\\w}/{e}/{d}");
assertEquals(Arrays.asList("a","c","b","e","d"),ut.getVariables());
assertEquals(Arrays.asList("c","b"),ut.getCustomVariables());
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testMatchWithMatrixOnClearPath2() throws Exception {
URITemplate uriTemplate=new URITemplate("/customers/{id}/orders/{order}");
MultivaluedMap values=new MetadataMap();
assertTrue(uriTemplate.match("/customers;123456/123/orders;456/3",values));
assertEquals("123",values.getFirst("id"));
assertEquals("3",values.getFirst("order"));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testMatchWithMatrixWithEmptyPath() throws Exception {
URITemplate uriTemplate=new URITemplate("/");
MultivaluedMap values=new MetadataMap();
boolean match=uriTemplate.match("/;a=b",values);
assertTrue(match);
String finalGroup=values.getFirst(URITemplate.FINAL_MATCH_GROUP);
assertEquals("/",finalGroup);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testBaseTail2(){
URITemplate uriTemplate=new URITemplate("/{base:.+base}/{tail}");
MultivaluedMap values=new MetadataMap();
assertFalse(uriTemplate.match("/base/tails",values));
assertFalse(uriTemplate.match("/base1/tails",values));
assertTrue(uriTemplate.match("/1base/tails",values));
assertEquals("1base",values.getFirst("base"));
assertEquals("tails",values.getFirst("tail"));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testMatchWithMatrixAndTemplate() throws Exception {
URITemplate uriTemplate=new URITemplate("/customers/{id}");
MultivaluedMap values=new MetadataMap();
boolean match=uriTemplate.match("/customers/123;123456/",values);
assertTrue(match);
String value=values.getFirst("id");
assertEquals("123;123456",value);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testMatchBasicTwoParametersVariation2() throws Exception {
URITemplate uriTemplate=new URITemplate("/customers/name/{name}/dep/{department}");
MultivaluedMap values=new MetadataMap();
boolean match=uriTemplate.match("/customers/name/john/dep/CS",values);
assertTrue(match);
String name=values.getFirst("name");
String department=values.getFirst("department");
assertEquals("john",name);
assertEquals("CS",department);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testMatchWithMatrixOnClearPath1() throws Exception {
URITemplate uriTemplate=new URITemplate("/customers/{id}");
MultivaluedMap values=new MetadataMap();
boolean match=uriTemplate.match("/customers;123456/123/",values);
assertTrue(match);
String value=values.getFirst("id");
assertEquals("123",value);
}
BooleanVerifier InternalCallVerifier
@Test public void testEscaping() throws Exception {
URITemplate uriTemplate=new URITemplate("/books/a.db");
MultivaluedMap values=new MetadataMap();
assertTrue(uriTemplate.match("/books/a.db",values));
assertFalse(uriTemplate.match("/books/adbc",values));
assertFalse(uriTemplate.match("/books/acdb",values));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testBaseTail1(){
URITemplate uriTemplate=new URITemplate("/{base:base.+}/{tail}");
MultivaluedMap values=new MetadataMap();
assertFalse(uriTemplate.match("/base/tails",values));
assertTrue(uriTemplate.match("/base1/tails",values));
assertEquals("base1",values.getFirst("base"));
assertEquals("tails",values.getFirst("tail"));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testURITemplateWithSubResourceVariation2() throws Exception {
URITemplate uriTemplate=new URITemplate("/customers");
MultivaluedMap values=new MetadataMap();
boolean match=uriTemplate.match("/customers/name/john/dep/CS",values);
assertTrue(match);
String subResourcePath=values.getFirst(URITemplate.FINAL_MATCH_GROUP);
assertEquals("/name/john/dep/CS",subResourcePath);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testExpressionWithNestedGroup2() throws Exception {
URITemplate uriTemplate=new URITemplate("/{resource:.+\\.(js|css|gif|png)}/bar");
MultivaluedMap values=new MetadataMap();
assertTrue(uriTemplate.match("/script.js/bar/baz",values));
assertEquals("script.js",values.getFirst("resource"));
String finalPath=values.getFirst(URITemplate.FINAL_MATCH_GROUP);
assertEquals("/baz",finalPath);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testTokenizerNoOpening(){
CurlyBraceTokenizer tok=new CurlyBraceTokenizer("foo}bar}baz");
assertEquals("foo}bar}baz",tok.next());
assertFalse(tok.hasNext());
}
BooleanVerifier InternalCallVerifier
@Test public void testFailCustomExpression() throws Exception {
URITemplate uriTemplate=new URITemplate("/books/{bookId:124}");
MultivaluedMap values=new MetadataMap();
boolean match=uriTemplate.match("/books/123/chapter/1",values);
assertFalse(match);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testMatchWithMatrixOnClearPath3() throws Exception {
URITemplate uriTemplate=new URITemplate("/{id}/customers/");
MultivaluedMap values=new MetadataMap();
boolean match=uriTemplate.match("/123/customers;123456/",values);
assertTrue(match);
String value=values.getFirst("id");
assertEquals("123",value);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testURITemplateWithSubResourceVariation3() throws Exception {
URITemplate uriTemplate=new URITemplate("/books/{bookId}/");
MultivaluedMap values=new MetadataMap();
boolean match=uriTemplate.match("/books/123/chapter/1",values);
assertTrue(match);
String subResourcePath=values.getFirst(URITemplate.FINAL_MATCH_GROUP);
assertEquals("/chapter/1",subResourcePath);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testMatchBasic() throws Exception {
URITemplate uriTemplate=new URITemplate("/customers/{id}");
MultivaluedMap values=new MetadataMap();
boolean match=uriTemplate.match("/customers/123/",values);
assertTrue(match);
String value=values.getFirst("id");
assertEquals("123",value);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testExpressionWithNestedGroup() throws Exception {
URITemplate uriTemplate=new URITemplate("/{resource:.+\\.(js|css|gif|png)}");
MultivaluedMap values=new MetadataMap();
assertTrue(uriTemplate.match("/script.js",values));
assertEquals("script.js",values.getFirst("resource"));
String finalPath=values.getFirst(URITemplate.FINAL_MATCH_GROUP);
assertEquals("/",finalPath);
values.clear();
assertTrue(uriTemplate.match("/script.js/bar",values));
assertEquals("script.js",values.getFirst("resource"));
finalPath=values.getFirst(URITemplate.FINAL_MATCH_GROUP);
assertEquals("/bar",finalPath);
values.clear();
assertFalse(uriTemplate.match("/script.pdf",values));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testURITemplateWithSubResourceVariation4() throws Exception {
URITemplate uriTemplate=new URITemplate("/");
MultivaluedMap values=new MetadataMap();
boolean match=uriTemplate.match("/books/123/chapter/1",values);
assertTrue(match);
String subResourcePath=values.getFirst(URITemplate.FINAL_MATCH_GROUP);
assertEquals("/books/123/chapter/1",subResourcePath);
}
BooleanVerifier InternalCallVerifier
@Test public void testValueWithRegExPlus() throws Exception {
URITemplate uriTemplate=new URITemplate("/books/{regex:ab+\\+}");
MultivaluedMap values=new MetadataMap();
assertTrue(uriTemplate.match("/books/ab+",values));
assertFalse(uriTemplate.match("/books/abb",values));
assertFalse(uriTemplate.match("/books/abb",values));
assertFalse(uriTemplate.match("/books/abc",values));
assertFalse(uriTemplate.match("/books/a",values));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testMultipleExpression2() throws Exception {
URITemplate uriTemplate=new URITemplate("/books/{bookId:123}/chapter/{id}");
MultivaluedMap values=new MetadataMap();
boolean match=uriTemplate.match("/books/123/chapter/1",values);
assertTrue(match);
assertEquals("123",values.getFirst("bookId"));
assertEquals("1",values.getFirst("id"));
String subResourcePath=values.getFirst(URITemplate.FINAL_MATCH_GROUP);
assertEquals("/",subResourcePath);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testMatchWithMatrixOnClearPath5() throws Exception {
URITemplate uriTemplate=new URITemplate("/customers");
MultivaluedMap values=new MetadataMap();
assertTrue(uriTemplate.match("/customers;a=b",values));
String finalGroup=values.getFirst(URITemplate.FINAL_MATCH_GROUP);
assertEquals("/",finalGroup);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testTokenizerNoClosing(){
CurlyBraceTokenizer tok=new CurlyBraceTokenizer("foo{bar}baz{blah");
assertEquals("foo",tok.next());
assertEquals("{bar}",tok.next());
assertEquals("baz",tok.next());
assertEquals("{blah",tok.next());
assertFalse(tok.hasNext());
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testURITemplateWithSubResource() throws Exception {
URITemplate uriTemplate=new URITemplate("/customers");
MultivaluedMap values=new MetadataMap();
boolean match=uriTemplate.match("/customers/123",values);
assertTrue(match);
String subResourcePath=values.getFirst(URITemplate.FINAL_MATCH_GROUP);
assertEquals("/123",subResourcePath);
}
BooleanVerifier InternalCallVerifier
@Test public void testValueWithManyLiteralPluses() throws Exception {
URITemplate uriTemplate=new URITemplate("/books/ab+++++");
MultivaluedMap values=new MetadataMap();
assertTrue(uriTemplate.match("/books/ab+++++",values));
assertFalse(uriTemplate.match("/books/ab++++++",values));
assertFalse(uriTemplate.match("/books/ab++++",values));
assertFalse(uriTemplate.match("/books/ab+++",values));
assertFalse(uriTemplate.match("/books/ab++",values));
assertFalse(uriTemplate.match("/books/ab+",values));
assertFalse(uriTemplate.match("/books/ab",values));
assertFalse(uriTemplate.match("/books/a",values));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testMatchBasicTwoParametersVariation1() throws Exception {
URITemplate uriTemplate=new URITemplate("/customers/{name}/{department}");
MultivaluedMap values=new MetadataMap();
boolean match=uriTemplate.match("/customers/john/CS",values);
assertTrue(match);
String name=values.getFirst("name");
String department=values.getFirst("department");
assertEquals("john",name);
assertEquals("CS",department);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testTokenizerNoBraces(){
CurlyBraceTokenizer tok=new CurlyBraceTokenizer("nobraces");
assertEquals("nobraces",tok.next());
assertFalse(tok.hasNext());
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testExpressionWithNestedGroupAndManySegments() throws Exception {
URITemplate uriTemplate=new URITemplate("/foo/{bar}{resource:(/format/[^/]+?)?}/baz");
MultivaluedMap values=new MetadataMap();
assertTrue(uriTemplate.match("/foo/1/format/2/baz/3",values));
assertEquals("1",values.getFirst("bar"));
assertEquals("/format/2",values.getFirst("resource"));
String finalPath=values.getFirst(URITemplate.FINAL_MATCH_GROUP);
assertEquals("/3",finalPath);
values.clear();
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testLiteralExpression() throws Exception {
URITemplate uriTemplate=new URITemplate("/bar");
MultivaluedMap values=new MetadataMap();
assertTrue(uriTemplate.match("/bar/baz",values));
String finalPath=values.getFirst(URITemplate.FINAL_MATCH_GROUP);
assertEquals("/baz",finalPath);
}
BooleanVerifier InternalCallVerifier
@Test public void testEncodedSpace() throws Exception {
URITemplate uriTemplate=new URITemplate("/1 2/%203");
MultivaluedMap values=new MetadataMap();
assertTrue(uriTemplate.match("/1%202/%203",values));
assertFalse(uriTemplate.match("/1 2/%203",values));
}
BooleanVerifier InternalCallVerifier
@Test public void testEscapingWildCard() throws Exception {
URITemplate uriTemplate=new URITemplate("/books/a*");
MultivaluedMap values=new MetadataMap();
assertTrue(uriTemplate.match("/books/a*",values));
assertFalse(uriTemplate.match("/books/a",values));
assertFalse(uriTemplate.match("/books/ac",values));
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testExpressionWithNestedGroupAndTwoVars2() throws Exception {
URITemplate uriTemplate=new URITemplate("/foo/{bar}{resource:(/format/[^/]+?)?}");
MultivaluedMap values=new MetadataMap();
assertTrue(uriTemplate.match("/foo/1/format",values));
assertEquals("1",values.getFirst("bar"));
assertEquals("/format",values.getFirst("resource"));
String finalPath=values.getFirst(URITemplate.FINAL_MATCH_GROUP);
assertEquals("/",finalPath);
values.clear();
assertTrue(uriTemplate.match("/foo/1/format/2",values));
assertEquals("1",values.getFirst("bar"));
assertEquals("/format/2",values.getFirst("resource"));
finalPath=values.getFirst(URITemplate.FINAL_MATCH_GROUP);
assertEquals("/",finalPath);
values.clear();
assertTrue(uriTemplate.match("/foo/1",values));
assertEquals("1",values.getFirst("bar"));
assertNull(values.getFirst("resource"));
finalPath=values.getFirst(URITemplate.FINAL_MATCH_GROUP);
assertEquals("/",finalPath);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testBasicCustomExpression2() throws Exception {
URITemplate uriTemplate=new URITemplate("/books/{bookId:123}");
MultivaluedMap values=new MetadataMap();
boolean match=uriTemplate.match("/books/123/chapter/1",values);
assertTrue(match);
assertEquals("123",values.getFirst("bookId"));
String subResourcePath=values.getFirst(URITemplate.FINAL_MATCH_GROUP);
assertEquals("/chapter/1",subResourcePath);
}
BooleanVerifier InternalCallVerifier
@Test public void testValueWithLiteralPlus() throws Exception {
URITemplate uriTemplate=new URITemplate("/books/ab+");
MultivaluedMap values=new MetadataMap();
assertTrue(uriTemplate.match("/books/ab+",values));
assertFalse(uriTemplate.match("/books/abb",values));
assertFalse(uriTemplate.match("/books/ab",values));
assertFalse(uriTemplate.match("/books/a",values));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testBasicCustomExpression3() throws Exception {
URITemplate uriTemplate=new URITemplate("/books/{bookId:\\d\\d\\d}");
MultivaluedMap values=new MetadataMap();
boolean match=uriTemplate.match("/books/123/chapter/1",values);
assertTrue(match);
assertEquals("123",values.getFirst("bookId"));
String subResourcePath=values.getFirst(URITemplate.FINAL_MATCH_GROUP);
assertEquals("/chapter/1",subResourcePath);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testExpressionWithTwoVars() throws Exception {
URITemplate uriTemplate=new URITemplate("/{tenant : [^/]*}/resource/{id}");
MultivaluedMap values=new MetadataMap();
boolean match=uriTemplate.match("/t1/resource/1",values);
assertTrue(match);
String tenant=values.getFirst("tenant");
assertEquals("t1",tenant);
String id=values.getFirst("id");
assertEquals("1",id);
String finalPath=values.getFirst(URITemplate.FINAL_MATCH_GROUP);
assertEquals("/",finalPath);
values.clear();
match=uriTemplate.match("//resource/1",values);
assertTrue(match);
tenant=values.getFirst("tenant");
assertEquals("",tenant);
id=values.getFirst("id");
assertEquals("1",id);
finalPath=values.getFirst(URITemplate.FINAL_MATCH_GROUP);
assertEquals("/",finalPath);
values.clear();
match=uriTemplate.match("/t1/resource/1/sub",values);
assertTrue(match);
tenant=values.getFirst("tenant");
assertEquals("t1",tenant);
id=values.getFirst("id");
assertEquals("1",id);
finalPath=values.getFirst(URITemplate.FINAL_MATCH_GROUP);
assertEquals("/sub",finalPath);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testBasicCustomExpression4() throws Exception {
URITemplate uriTemplate=new URITemplate("/books/{bookId:...\\.}");
MultivaluedMap values=new MetadataMap();
assertTrue(uriTemplate.match("/books/123.",values));
assertEquals("123.",values.getFirst("bookId"));
values.clear();
assertTrue(uriTemplate.match("/books/abc.",values));
assertEquals("abc.",values.getFirst("bookId"));
assertFalse(uriTemplate.match("/books/abcd",values));
assertFalse(uriTemplate.match("/books/abc",values));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testMatchWithMatrixWithEmptyPath2() throws Exception {
URITemplate uriTemplate=new URITemplate("/");
MultivaluedMap values=new MetadataMap();
boolean match=uriTemplate.match("/;a=b/b/c",values);
assertTrue(match);
String finalGroup=values.getFirst(URITemplate.FINAL_MATCH_GROUP);
assertEquals("/b/c",finalGroup);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testExpressionWithNestedGroupAndTwoVars() throws Exception {
URITemplate uriTemplate=new URITemplate("/foo/{bar}/{resource:.+\\.(js|css|gif|png)}");
MultivaluedMap values=new MetadataMap();
assertTrue(uriTemplate.match("/foo/1/script.js",values));
assertEquals("1",values.getFirst("bar"));
assertEquals("script.js",values.getFirst("resource"));
String finalPath=values.getFirst(URITemplate.FINAL_MATCH_GROUP);
assertEquals("/",finalPath);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testTokenizerNesting(){
CurlyBraceTokenizer tok=new CurlyBraceTokenizer("foo{bar{baz}}blah");
assertEquals("foo",tok.next());
assertEquals("{bar{baz}}",tok.next());
assertEquals("blah",tok.next());
assertFalse(tok.hasNext());
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testTokenizerNoNesting(){
CurlyBraceTokenizer tok=new CurlyBraceTokenizer("foo{bar}baz");
assertEquals("foo",tok.next());
assertEquals("{bar}",tok.next());
assertEquals("baz",tok.next());
assertFalse(tok.hasNext());
}
Class: org.apache.cxf.jaxrs.model.wadl.ServerProviderFactoryTest BooleanVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testCustomTestAndWadlHandler(){
ServerProviderFactory pf=ServerProviderFactory.getInstance();
assertEquals(1,pf.getPreMatchContainerRequestFilters().size());
assertTrue(pf.getPreMatchContainerRequestFilters().get(0).getProvider() instanceof WadlGenerator);
List providers=new ArrayList();
WadlGenerator wg=new WadlGenerator();
providers.add(wg);
TestHandler th=new TestHandler();
providers.add(th);
pf.setUserProviders(providers);
assertEquals(2,pf.getPreMatchContainerRequestFilters().size());
assertSame(wg,pf.getPreMatchContainerRequestFilters().get(0).getProvider());
assertSame(th,pf.getPreMatchContainerRequestFilters().get(1).getProvider());
}
BooleanVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testCustomTestHandler(){
ServerProviderFactory pf=ServerProviderFactory.getInstance();
assertEquals(1,pf.getPreMatchContainerRequestFilters().size());
assertTrue(pf.getPreMatchContainerRequestFilters().get(0).getProvider() instanceof WadlGenerator);
TestHandler th=new TestHandler();
pf.setUserProviders(Collections.singletonList(th));
assertEquals(2,pf.getPreMatchContainerRequestFilters().size());
assertTrue(pf.getPreMatchContainerRequestFilters().get(0).getProvider() instanceof WadlGenerator);
assertSame(th,pf.getPreMatchContainerRequestFilters().get(1).getProvider());
}
BooleanVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testCustomWadlHandler(){
ServerProviderFactory pf=ServerProviderFactory.getInstance();
assertEquals(1,pf.getPreMatchContainerRequestFilters().size());
assertTrue(pf.getPreMatchContainerRequestFilters().get(0).getProvider() instanceof WadlGenerator);
WadlGenerator wg=new WadlGenerator();
pf.setUserProviders(Collections.singletonList(wg));
assertEquals(1,pf.getPreMatchContainerRequestFilters().size());
assertTrue(pf.getPreMatchContainerRequestFilters().get(0).getProvider() instanceof WadlGenerator);
assertSame(wg,pf.getPreMatchContainerRequestFilters().get(0).getProvider());
}
Class: org.apache.cxf.jaxrs.model.wadl.WadlGeneratorJsonTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testWadlInJsonFormat() throws Exception {
ClassResourceInfo cri=ResourceUtils.createClassResourceInfo(BookChapters.class,BookChapters.class,true,true);
final Message m=mockMessage("http://localhost:8080/baz","/bookstore/1",WadlGenerator.WADL_QUERY,cri);
Map> headers=new HashMap>();
headers.put("Accept",Collections.singletonList("application/json"));
m.put(Message.PROTOCOL_HEADERS,headers);
WadlGenerator wg=new WadlGenerator(){
public void filter( ContainerRequestContext context){
super.doFilter(context,m);
}
}
;
wg.setUseJaxbContextForQnames(false);
wg.setIgnoreMessageWriters(false);
wg.setExternalLinks(Collections.singletonList("json.schema"));
Response r=handleRequest(wg,m);
assertEquals("application/json",r.getMetadata().getFirst("Content-Type").toString());
ByteArrayOutputStream os=new ByteArrayOutputStream();
new JSONProvider().writeTo((Document)r.getEntity(),Document.class,Document.class,new Annotation[]{},MediaType.APPLICATION_JSON_TYPE,new MetadataMap(),os);
String s=os.toString();
String expected1="{\"application\":{\"grammars\":{\"include\":{\"@href\":\"http://localhost:8080/baz" + "/json.schema\"}},\"resources\":{\"@base\":\"http://localhost:8080/baz\"," + "\"resource\":{\"@path\":\"/bookstore/{id}\"";
assertTrue(s.startsWith(expected1));
String expected2="\"response\":{\"representation\":[{\"@mediaType\":\"application/xml\"}," + "{\"@element\":\"Chapter\",\"@mediaType\":\"application/json\"}]}";
assertTrue(s.contains(expected2));
}
Class: org.apache.cxf.jaxrs.model.wadl.WadlGeneratorTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testMultipleRootResources() throws Exception {
WadlGenerator wg=new WadlGenerator();
wg.setDefaultMediaType(WadlGenerator.WADL_TYPE.toString());
ClassResourceInfo cri1=ResourceUtils.createClassResourceInfo(BookStore.class,BookStore.class,true,true);
ClassResourceInfo cri2=ResourceUtils.createClassResourceInfo(Orders.class,Orders.class,true,true);
List cris=new ArrayList();
cris.add(cri1);
cris.add(cri2);
Message m=mockMessage("http://localhost:8080/baz","",WadlGenerator.WADL_QUERY,cris);
Response r=handleRequest(wg,m);
assertEquals(WadlGenerator.WADL_TYPE.toString(),r.getMetadata().getFirst(HttpHeaders.CONTENT_TYPE).toString());
String wadl=r.getEntity().toString();
Document doc=StaxUtils.read(new StringReader(wadl));
checkGrammars(doc.getDocumentElement(),"thebook","books","thebook2s","thebook2","thechapter");
List els=getWadlResourcesInfo(doc,"http://localhost:8080/baz",2);
checkBookStoreInfo(els.get(0),"prefix1:thebook","prefix1:thebook2","prefix1:thechapter");
Element orderResource=els.get(1);
assertEquals("/orders",orderResource.getAttribute("path"));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testCustomSchemaWithImportJaxbContextPrefixes() throws Exception {
WadlGenerator wg=new WadlGenerator();
wg.setSchemaLocations(Collections.singletonList("classpath:/books.xsd"));
ClassResourceInfo cri=ResourceUtils.createClassResourceInfo(BookStore.class,BookStore.class,true,true);
Message m=mockMessage("http://localhost:8080/baz","/bar",WadlGenerator.WADL_QUERY,cri);
Response r=handleRequest(wg,m);
checkResponse(r);
Document doc=StaxUtils.read(new StringReader(r.getEntity().toString()));
List grammarEls=DOMUtils.getChildrenWithName(doc.getDocumentElement(),WadlGenerator.WADL_NS,"grammars");
assertEquals(1,grammarEls.size());
List schemasEls=DOMUtils.getChildrenWithName(grammarEls.get(0),Constants.URI_2001_SCHEMA_XSD,"schema");
assertEquals(1,schemasEls.size());
assertEquals("http://books",schemasEls.get(0).getAttribute("targetNamespace"));
List elementEls=DOMUtils.getChildrenWithName(schemasEls.get(0),Constants.URI_2001_SCHEMA_XSD,"element");
assertEquals(1,elementEls.size());
assertTrue(checkElement(elementEls,"books","books"));
List complexTypesEls=DOMUtils.getChildrenWithName(schemasEls.get(0),Constants.URI_2001_SCHEMA_XSD,"complexType");
assertEquals(1,complexTypesEls.size());
assertTrue(checkComplexType(complexTypesEls,"books"));
List importEls=DOMUtils.getChildrenWithName(schemasEls.get(0),Constants.URI_2001_SCHEMA_XSD,"import");
assertEquals(1,importEls.size());
assertEquals("http://localhost:8080/baz/book1.xsd",importEls.get(0).getAttribute("schemaLocation"));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testRootResourceWithSingleSlash() throws Exception {
WadlGenerator wg=new WadlGenerator();
ClassResourceInfo cri=ResourceUtils.createClassResourceInfo(BookStoreWithSingleSlash.class,BookStoreWithSingleSlash.class,true,true);
Message m=mockMessage("http://localhost:8080/baz","/",WadlGenerator.WADL_QUERY,cri);
Response r=handleRequest(wg,m);
checkResponse(r);
Document doc=StaxUtils.read(new StringReader(r.getEntity().toString()));
List rootEls=getWadlResourcesInfo(doc,"http://localhost:8080/baz",1);
assertEquals(1,rootEls.size());
Element resource=rootEls.get(0);
assertEquals("/",resource.getAttribute("path"));
List resourceEls=DOMUtils.getChildrenWithName(resource,WadlGenerator.WADL_NS,"resource");
assertEquals(1,resourceEls.size());
assertEquals("book",resourceEls.get(0).getAttribute("path"));
verifyParameters(resourceEls.get(0),1,new Param("id","template","xs:int"));
checkGrammars(doc.getDocumentElement(),"thebook",null,"thechapter");
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testTwoSchemasSameNs() throws Exception {
WadlGenerator wg=new WadlGenerator();
wg.setApplicationTitle("My Application");
wg.setNamespacePrefix("ns");
ClassResourceInfo cri=ResourceUtils.createClassResourceInfo(TestResource.class,TestResource.class,true,true);
Message m=mockMessage("http://localhost:8080/baz","/",WadlGenerator.WADL_QUERY,cri);
Response r=handleRequest(wg,m);
checkResponse(r);
Document doc=StaxUtils.read(new StringReader(r.getEntity().toString()));
checkDocs(doc.getDocumentElement(),"My Application","","");
List grammarEls=DOMUtils.getChildrenWithName(doc.getDocumentElement(),WadlGenerator.WADL_NS,"grammars");
assertEquals(1,grammarEls.size());
List schemasEls=DOMUtils.getChildrenWithName(grammarEls.get(0),Constants.URI_2001_SCHEMA_XSD,"schema");
assertEquals(2,schemasEls.size());
assertEquals("http://example.com/test",schemasEls.get(0).getAttribute("targetNamespace"));
assertEquals("http://example.com/test",schemasEls.get(1).getAttribute("targetNamespace"));
List reps=DOMUtils.findAllElementsByTagNameNS(doc.getDocumentElement(),WadlGenerator.WADL_NS,"representation");
assertEquals(2,reps.size());
assertEquals("ns1:testCompositeObject",reps.get(0).getAttribute("element"));
assertEquals("ns1:testCompositeObject",reps.get(1).getAttribute("element"));
}
InternalCallVerifier NullVerifier
@Test public void testNoWadl(){
WadlGenerator wg=new WadlGenerator();
Message m=new MessageImpl();
m.setExchange(new ExchangeImpl());
assertNull(handleRequest(wg,m));
}
Class: org.apache.cxf.jaxrs.provider.BinaryDataProviderTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@SuppressWarnings({"unchecked","rawtypes"}) @Test public void testReadFrom() throws Exception {
MessageBodyReader p=new BinaryDataProvider();
byte[] bytes=(byte[])p.readFrom(byte[].class,byte[].class,new Annotation[]{},MediaType.APPLICATION_OCTET_STREAM_TYPE,new MetadataMap(),new ByteArrayInputStream("hi".getBytes()));
assertTrue(Arrays.equals(new String("hi").getBytes(),bytes));
InputStream is=(InputStream)p.readFrom(InputStream.class,InputStream.class,new Annotation[]{},MediaType.APPLICATION_OCTET_STREAM_TYPE,new MetadataMap(),new ByteArrayInputStream("hi".getBytes()));
bytes=IOUtils.readBytesFromStream(is);
assertTrue(Arrays.equals(new String("hi").getBytes(),bytes));
Reader r=(Reader)p.readFrom(Reader.class,Reader.class,new Annotation[]{},MediaType.APPLICATION_OCTET_STREAM_TYPE,new MetadataMap(),new ByteArrayInputStream("hi".getBytes()));
assertEquals(IOUtils.toString(r),"hi");
StreamingOutput so=(StreamingOutput)p.readFrom(StreamingOutput.class,StreamingOutput.class,new Annotation[]{},MediaType.APPLICATION_OCTET_STREAM_TYPE,new MetadataMap(),new ByteArrayInputStream("hi".getBytes()));
ByteArrayOutputStream baos=new ByteArrayOutputStream();
so.write(baos);
bytes=baos.toByteArray();
assertTrue(Arrays.equals(new String("hi").getBytes(),bytes));
}
Class: org.apache.cxf.jaxrs.provider.DataSourceProviderTest InternalCallVerifier EqualityVerifier
@Test public void testReadDataHandler() throws Exception {
DataSourceProvider p=new DataSourceProvider();
DataHandler ds=(DataHandler)p.readFrom(DataHandler.class,null,new Annotation[]{},MediaType.valueOf("image/png"),new MetadataMap(),new ByteArrayInputStream("image".getBytes()));
assertEquals("image",IOUtils.readStringFromStream(ds.getDataSource().getInputStream()));
}
InternalCallVerifier EqualityVerifier
@Test public void testReadDataSource() throws Exception {
DataSourceProvider p=new DataSourceProvider();
DataSource ds=(DataSource)p.readFrom(DataSource.class,null,new Annotation[]{},MediaType.valueOf("image/png"),new MetadataMap(),new ByteArrayInputStream("image".getBytes()));
assertEquals("image",IOUtils.readStringFromStream(ds.getInputStream()));
}
Class: org.apache.cxf.jaxrs.provider.FormEncodingProviderTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@SuppressWarnings("unchecked") @Test public void testEncoded() throws Exception {
String values="foo=1+2&bar=1+3";
@SuppressWarnings("rawtypes") FormEncodingProvider ferp=new FormEncodingProvider();
MultivaluedMap mvMap=(MultivaluedMap)ferp.readFrom(MultivaluedMap.class,null,new Annotation[]{CustomMap.class.getAnnotations()[0]},MediaType.APPLICATION_FORM_URLENCODED_TYPE,null,new ByteArrayInputStream(values.getBytes()));
assertEquals("Wrong entry for foo","1+2",mvMap.getFirst("foo"));
assertEquals("Wrong entry for boo","1+3",mvMap.getFirst("bar"));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testMultiLines() throws Exception {
String values="foo=1+2&bar=line1%0D%0Aline+2&baz=4";
FormEncodingProvider ferp=new FormEncodingProvider();
MultivaluedMap mvMap=ferp.readFrom(CustomMap.class,null,new Annotation[]{},MediaType.APPLICATION_FORM_URLENCODED_TYPE,null,new ByteArrayInputStream(values.getBytes()));
assertEquals(3,mvMap.size());
assertEquals(1,mvMap.get("foo").size());
assertEquals(1,mvMap.get("bar").size());
assertEquals(1,mvMap.get("baz").size());
assertEquals("Wrong entry for foo","1 2",mvMap.getFirst("foo"));
assertEquals("Wrong entry line for bar",HttpUtils.urlDecode("line1%0D%0Aline+2"),mvMap.get("bar").get(0));
assertEquals("Wrong entry for baz","4",mvMap.getFirst("baz"));
}
InternalCallVerifier EqualityVerifier
@SuppressWarnings("unchecked") @Test public void testReadFromMultiples() throws Exception {
InputStream is=getClass().getResourceAsStream("multiValPostBody.txt");
@SuppressWarnings("rawtypes") FormEncodingProvider ferp=new FormEncodingProvider();
MultivaluedMap mvMap=(MultivaluedMap)ferp.readFrom(MultivaluedMap.class,null,new Annotation[]{},MediaType.APPLICATION_FORM_URLENCODED_TYPE,null,is);
List vals=mvMap.get("foo");
assertEquals("Wrong size for foo params",2,vals.size());
assertEquals("Wrong size for foo params",1,mvMap.get("boo").size());
assertEquals("Wrong entry for foo 0","bar",vals.get(0));
assertEquals("Wrong entry for foo 1","bar2",vals.get(1));
assertEquals("Wrong entry for boo","far",mvMap.getFirst("boo"));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testCustomMapImpl() throws Exception {
String values="foo=1+2&bar=1+3&baz=4";
FormEncodingProvider ferp=new FormEncodingProvider();
MultivaluedMap mvMap=ferp.readFrom(CustomMap.class,null,new Annotation[]{},MediaType.APPLICATION_FORM_URLENCODED_TYPE,null,new ByteArrayInputStream(values.getBytes()));
assertEquals(3,mvMap.size());
assertEquals(1,mvMap.get("foo").size());
assertEquals(1,mvMap.get("bar").size());
assertEquals(1,mvMap.get("baz").size());
assertEquals("Wrong entry for foo","1 2",mvMap.getFirst("foo"));
assertEquals("Wrong entry for boo","1 3",mvMap.getFirst("bar"));
assertEquals("Wrong entry for baz","4",mvMap.getFirst("baz"));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@SuppressWarnings("unchecked") @Test public void testReadFromISO() throws Exception {
String eWithAcute="\u00E9";
String helloStringUTF16="name=F" + eWithAcute + "lix";
byte[] iso88591bytes=helloStringUTF16.getBytes("ISO-8859-1");
String helloStringISO88591=new String(iso88591bytes,"ISO-8859-1");
@SuppressWarnings("rawtypes") FormEncodingProvider ferp=new FormEncodingProvider();
MultivaluedMap mvMap=(MultivaluedMap)ferp.readFrom(MultivaluedMap.class,null,new Annotation[]{},MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED + ";charset=ISO-8859-1"),null,new ByteArrayInputStream(iso88591bytes));
String value=mvMap.getFirst("name");
assertEquals(helloStringISO88591,"name=" + value);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@SuppressWarnings("unchecked") @Test public void testReadChineeseChars() throws Exception {
String s="name=䏿–‡";
@SuppressWarnings("rawtypes") FormEncodingProvider ferp=new FormEncodingProvider();
MultivaluedMap mvMap=(MultivaluedMap)ferp.readFrom(MultivaluedMap.class,null,new Annotation[]{},MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED + ";charset=UTF-8"),null,new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8)));
String value=mvMap.getFirst("name");
assertEquals(s,"name=" + value);
}
InternalCallVerifier EqualityVerifier
@Test public void testReadFrom() throws Exception {
@SuppressWarnings("rawtypes") FormEncodingProvider ferp=new FormEncodingProvider();
InputStream is=getClass().getResourceAsStream("singleValPostBody.txt");
@SuppressWarnings("unchecked") MultivaluedMap mvMap=(MultivaluedMap)ferp.readFrom(MultivaluedMap.class,null,new Annotation[]{},MediaType.APPLICATION_FORM_URLENCODED_TYPE,null,is);
assertEquals("Wrong entry for foo","bar",mvMap.getFirst("foo"));
assertEquals("Wrong entry for boo","far",mvMap.getFirst("boo"));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@SuppressWarnings("unchecked") @Test public void testDecoded() throws Exception {
String values="foo=1+2&bar=1+3";
@SuppressWarnings("rawtypes") FormEncodingProvider ferp=new FormEncodingProvider();
@SuppressWarnings("rawtypes") MultivaluedMap mvMap=(MultivaluedMap)ferp.readFrom((Class)MultivaluedMap.class,null,new Annotation[]{},MediaType.APPLICATION_FORM_URLENCODED_TYPE,null,new ByteArrayInputStream(values.getBytes()));
assertEquals("Wrong entry for foo","1 2",mvMap.getFirst("foo"));
assertEquals("Wrong entry for boo","1 3",mvMap.getFirst("bar"));
}
InternalCallVerifier EqualityVerifier
@Test public void testReadFromForm() throws Exception {
FormEncodingProvider
Class: org.apache.cxf.jaxrs.provider.JAXBElementProviderTest InternalCallVerifier NullVerifier
@Test public void testSetSchemasFromDisk() throws Exception {
JAXBElementProvider> provider=new JAXBElementProvider();
List locations=new ArrayList();
String loc=getClass().getClassLoader().getResource("test.xsd").toURI().getPath();
locations.add("file:" + loc);
provider.setSchemaLocations(locations);
Schema s=provider.getSchema();
assertNotNull("schema can not be read from disk",s);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testInNsElementsFromLocals() throws Exception {
String data="" + "B A ";
JAXBElementProvider provider=new JAXBElementProvider();
Map map=new HashMap();
map.put("tagholder","{http://tags}tagholder");
map.put("thetag","{http://tags}thetag");
provider.setInTransformElements(map);
ByteArrayInputStream is=new ByteArrayInputStream(data.getBytes());
Object o=provider.readFrom(TagVO2Holder.class,TagVO2Holder.class,new Annotation[0],MediaType.TEXT_XML_TYPE,new MetadataMap(),is);
TagVO2Holder holder=(TagVO2Holder)o;
TagVO2 tag2=holder.getTagValue();
assertEquals("A",tag2.getName());
assertEquals("B",tag2.getGroup());
}
BooleanVerifier InternalCallVerifier
@Test public void testResponseIsNotReadable2(){
JAXBElementProvider p=new JAXBElementProvider();
p.setUnmarshallAsJaxbElement(true);
assertFalse(p.isReadable(Response.class,Response.class,new Annotation[]{},MediaType.APPLICATION_XML_TYPE));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testWriteWithoutXmlRootElementWithPackageInfo() throws Exception {
JAXBElementProvider provider=new JAXBElementProvider();
provider.setMarshallAsJaxbElement(true);
Book2NoRootElement book=new Book2NoRootElement(333);
ByteArrayOutputStream bos=new ByteArrayOutputStream();
provider.writeTo(book,Book2NoRootElement.class,Book2NoRootElement.class,new Annotation[0],MediaType.TEXT_XML_TYPE,new MetadataMap(),bos);
assertTrue(bos.toString().contains("book2"));
assertTrue(bos.toString().contains("http://superbooks"));
provider.setUnmarshallAsJaxbElement(true);
ByteArrayInputStream is=new ByteArrayInputStream(bos.toByteArray());
Book2NoRootElement book2=provider.readFrom(Book2NoRootElement.class,Book2NoRootElement.class,new Annotation[0],MediaType.TEXT_XML_TYPE,new MetadataMap(),is);
assertEquals(book2.getId(),book.getId());
}
InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testSingleJAXBContext() throws Exception {
ClassResourceInfo cri=ResourceUtils.createClassResourceInfo(JAXBResource.class,JAXBResource.class,true,true);
JAXBElementProvider provider=new JAXBElementProvider();
provider.setSingleJaxbContext(true);
provider.init(Collections.singletonList(cri));
JAXBContext bookContext=provider.getJAXBContext(Book.class,Book.class);
assertNotNull(bookContext);
JAXBContext superBookContext=provider.getJAXBContext(SuperBook.class,SuperBook.class);
assertSame(bookContext,superBookContext);
JAXBContext book2Context=provider.getJAXBContext(Book2.class,Book2.class);
assertSame(bookContext,book2Context);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testReadParamJAXBElement() throws Exception {
String xml=" " + "a ";
JAXBElementProvider provider=new JAXBElementProvider();
ParamJAXBElement jaxbElement=provider.readFrom(ParamJAXBElement.class,ParamJAXBElement.class,new Annotation[0],MediaType.TEXT_XML_TYPE,new MetadataMap(),new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
ParamType param=jaxbElement.getValue();
assertEquals("a",param.getComment());
}
InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testExtraClass() throws Exception {
ClassResourceInfo cri=ResourceUtils.createClassResourceInfo(BookStore.class,BookStore.class,true,true);
JAXBElementProvider provider=new JAXBElementProvider();
provider.setSingleJaxbContext(true);
provider.setExtraClass(new Class[]{SuperBook.class});
provider.init(Collections.singletonList(cri));
JAXBContext bookContext=provider.getJAXBContext(Book.class,Book.class);
assertNotNull(bookContext);
JAXBContext superBookContext=provider.getJAXBContext(SuperBook.class,SuperBook.class);
assertSame(bookContext,superBookContext);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testWriteWithoutXmlRootElementObjectFactory() throws Exception {
JAXBElementProvider provider=new JAXBElementProvider();
provider.setJaxbElementClassMap(Collections.singletonMap(org.apache.cxf.jaxrs.fortest.jaxb.SuperBook2.class.getName(),"{http://books}SuperBook2"));
org.apache.cxf.jaxrs.fortest.jaxb.SuperBook2 b=new org.apache.cxf.jaxrs.fortest.jaxb.SuperBook2("CXF in Action",123L,124L);
ByteArrayOutputStream bos=new ByteArrayOutputStream();
provider.writeTo(b,org.apache.cxf.jaxrs.fortest.jaxb.SuperBook2.class,org.apache.cxf.jaxrs.fortest.jaxb.SuperBook2.class,new Annotation[0],MediaType.TEXT_XML_TYPE,new MetadataMap(),bos);
JAXBElementProvider provider2=new JAXBElementProvider();
ByteArrayInputStream is=new ByteArrayInputStream(bos.toByteArray());
org.apache.cxf.jaxrs.fortest.jaxb.SuperBook2 book=provider2.readFrom(org.apache.cxf.jaxrs.fortest.jaxb.SuperBook2.class,org.apache.cxf.jaxrs.fortest.jaxb.SuperBook2.class,new Annotation[0],MediaType.TEXT_XML_TYPE,new MetadataMap(),is);
assertEquals(124L,book.getSuperId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@SuppressWarnings({"rawtypes","unchecked"}) @Test public void testReadJAXBElement() throws Exception {
String xml="123 CXF in Action ";
JAXBElementProvider provider=new JAXBElementProvider();
JAXBElement jaxbElement=provider.readFrom(JAXBElement.class,Book.class,new Annotation[0],MediaType.TEXT_XML_TYPE,new MetadataMap(),new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
Book book=jaxbElement.getValue();
assertEquals(123L,book.getId());
assertEquals("CXF in Action",book.getName());
}
InternalCallVerifier NullVerifier
@Test public void testSetSchemasFromAnnotation(){
JAXBElementProvider> provider=new JAXBElementProvider();
ClassResourceInfo cri=ResourceUtils.createClassResourceInfo(JAXBResource.class,JAXBResource.class,true,true);
provider.init(Collections.singletonList(cri));
Schema s=provider.getSchema();
assertNotNull("schema can not be read from classpath",s);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testWriteWithXmlRootElementAndPackageInfo() throws Exception {
JAXBElementProvider provider=new JAXBElementProvider();
Book2 book=new Book2(333);
ByteArrayOutputStream bos=new ByteArrayOutputStream();
provider.writeTo(book,Book2.class,Book2.class,new Annotation[0],MediaType.TEXT_XML_TYPE,new MetadataMap(),bos);
assertTrue(bos.toString().contains("thebook2"));
assertTrue(bos.toString().contains("http://superbooks"));
ByteArrayInputStream is=new ByteArrayInputStream(bos.toByteArray());
Book2 book2=provider.readFrom(Book2.class,Book2.class,new Annotation[0],MediaType.TEXT_XML_TYPE,new MetadataMap(),is);
assertEquals(book2.getId(),book.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testReadSuperBookWithJaxbElementAndTransform() throws Exception {
final String data="" + "superbook 111 " + " ";
JAXBElementProvider provider=new JAXBElementProvider();
provider.setUnmarshallAsJaxbElement(true);
provider.setInTransformElements(Collections.singletonMap("{http://books}*",""));
ByteArrayInputStream is=new ByteArrayInputStream(data.getBytes());
BookNoRootElement book=provider.readFrom(BookNoRootElement.class,BookNoRootElement.class,new Annotation[0],MediaType.TEXT_XML_TYPE,new MetadataMap(),is);
assertEquals(111L,book.getId());
assertEquals("superbook",book.getName());
}
BooleanVerifier InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testPackageContextObjectFactory(){
JAXBElementProvider p=new JAXBElementProvider();
assertTrue(p.isReadable(org.apache.cxf.jaxrs.fortest.jaxb.Book.class,org.apache.cxf.jaxrs.fortest.jaxb.Book.class,new Annotation[]{},MediaType.APPLICATION_XML_TYPE));
try {
JAXBContext context=p.getPackageContext(org.apache.cxf.jaxrs.fortest.jaxb.Book.class);
JAXBContext context2=p.getPackageContext(org.apache.cxf.jaxrs.fortest.jaxb.Book.class);
assertNotNull(context);
assertNotNull(context2);
assertSame(context,context2);
}
finally {
p.clearContexts();
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testReadSuperBookWithJaxbElement() throws Exception {
final String data="" + "superbook 111 " + " ";
JAXBElementProvider provider=new JAXBElementProvider();
provider.setUnmarshallAsJaxbElement(true);
ByteArrayInputStream is=new ByteArrayInputStream(data.getBytes());
BookNoRootElement book=provider.readFrom(BookNoRootElement.class,BookNoRootElement.class,new Annotation[0],MediaType.TEXT_XML_TYPE,new MetadataMap(),is);
assertEquals(111L,book.getId());
assertEquals("superbook",book.getName());
}
InternalCallVerifier NullVerifier
@Test public void testSetSchemasFromClasspath(){
JAXBElementProvider> provider=new JAXBElementProvider();
List locations=new ArrayList();
locations.add("classpath:/test.xsd");
provider.setSchemaLocations(locations);
Schema s=provider.getSchema();
assertNotNull("schema can not be read from classpath",s);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testInDropElement() throws Exception {
String data="b a
" + " ";
JAXBElementProvider provider=new JAXBElementProvider();
provider.setInDropElements(Collections.singletonList("Extra"));
ByteArrayInputStream is=new ByteArrayInputStream(data.getBytes());
Object o=provider.readFrom(ManyTags.class,ManyTags.class,new Annotation[0],MediaType.TEXT_XML_TYPE,new MetadataMap(),is);
ManyTags holder=(ManyTags)o;
assertNotNull(holder);
TagVO tag=holder.getTags().getTags().get(0);
assertEquals("a",tag.getName());
assertEquals("b",tag.getGroup());
}
APIUtilityVerifier BranchVerifier UtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testWriteWithFailedValidation() throws Exception {
JAXBElementProvider provider=new JAXBElementProvider();
List locations=new ArrayList();
String loc=getClass().getClassLoader().getResource("test.xsd").toURI().getPath();
locations.add("file:" + loc);
provider.setSchemaLocations(locations);
Schema s=provider.getSchema();
assertNotNull("schema can not be read from disk",s);
provider.setValidateOutput(true);
provider.setValidateBeforeWrite(true);
try {
provider.writeTo(new Book2(),Book2.class,Book2.class,new Annotation[]{},MediaType.TEXT_XML_TYPE,new MetadataMap(),new ByteArrayOutputStream());
fail("Validation exception expected");
}
catch ( Exception ex) {
Throwable cause=ex.getCause();
boolean english="en".equals(java.util.Locale.getDefault().getLanguage());
if (english) {
assertTrue(cause.getMessage().contains("Cannot find the declaration of element"));
}
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testReadFromISO() throws Exception {
String eWithAcute="\u00E9";
String nameStringUTF16="F" + eWithAcute + "lix";
String bookStringUTF16="" + "" + nameStringUTF16 + " ";
byte[] iso88591bytes=bookStringUTF16.getBytes("ISO-8859-1");
JAXBElementProvider p=new JAXBElementProvider();
Book book=p.readFrom(Book.class,null,new Annotation[]{},MediaType.valueOf(MediaType.APPLICATION_XML),null,new ByteArrayInputStream(iso88591bytes));
assertEquals(book.getName(),nameStringUTF16);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testInNsElementsFromLocalsWildcard2() throws Exception {
String data="" + "B " + "A ";
JAXBElementProvider provider=new JAXBElementProvider();
Map map=new LinkedHashMap();
map.put("group","group");
map.put("name","name");
map.put("{http://tags2}*","{http://tags}*");
provider.setInTransformElements(map);
ByteArrayInputStream is=new ByteArrayInputStream(data.getBytes());
Object o=provider.readFrom(TagVO2Holder.class,TagVO2Holder.class,new Annotation[0],MediaType.TEXT_XML_TYPE,new MetadataMap(),is);
TagVO2Holder holder=(TagVO2Holder)o;
TagVO2 tag2=holder.getTagValue();
assertEquals("A",tag2.getName());
assertEquals("B",tag2.getGroup());
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testWriteWithValidation() throws Exception {
JAXBElementProvider provider=new JAXBElementProvider();
List locations=new ArrayList();
String loc=getClass().getClassLoader().getResource("book1.xsd").toURI().getPath();
locations.add(loc);
provider.setSchemaLocations(locations);
Schema s=provider.getSchema();
assertNotNull("schema can not be read from disk",s);
provider.setValidateOutput(true);
provider.setValidateBeforeWrite(true);
Book2 book2=new Book2();
ByteArrayOutputStream bos=new ByteArrayOutputStream();
provider.writeTo(book2,Book2.class,Book2.class,new Annotation[]{},MediaType.TEXT_XML_TYPE,new MetadataMap(),bos);
assertTrue(bos.toString().contains("http://superbooks"));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testReadChineeseChars() throws Exception {
String nameStringUTF16="䏿–‡";
String bookStringUTF16="" + nameStringUTF16 + " ";
JAXBElementProvider p=new JAXBElementProvider();
Book book=p.readFrom(Book.class,null,new Annotation[]{},MediaType.valueOf(MediaType.APPLICATION_XML + ";charset=UTF-8"),null,new ByteArrayInputStream(bookStringUTF16.getBytes(StandardCharsets.UTF_8)));
assertEquals(book.getName(),nameStringUTF16);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testInNsElementsFromLocalsWildcard() throws Exception {
String data="" + "B A ";
JAXBElementProvider provider=new JAXBElementProvider();
Map map=new LinkedHashMap();
map.put("group","group");
map.put("name","name");
map.put("*","{http://tags}*");
provider.setInTransformElements(map);
ByteArrayInputStream is=new ByteArrayInputStream(data.getBytes());
Object o=provider.readFrom(TagVO2Holder.class,TagVO2Holder.class,new Annotation[0],MediaType.TEXT_XML_TYPE,new MetadataMap(),is);
TagVO2Holder holder=(TagVO2Holder)o;
TagVO2 tag2=holder.getTagValue();
assertEquals("A",tag2.getName());
assertEquals("B",tag2.getGroup());
}
APIUtilityVerifier IterativeVerifier InternalCallVerifier EqualityVerifier
@Test public void testGenericsAndSingleContext2() throws Exception {
ClassResourceInfo cri=ResourceUtils.createClassResourceInfo(XmlListResource.class,XmlListResource.class,true,true);
JAXBElementProvider> provider=new JAXBElementProvider();
provider.setSingleJaxbContext(true);
provider.init(Collections.singletonList(cri));
List list=new ArrayList();
for (int i=0; i < 10; i++) {
org.apache.cxf.jaxrs.fortest.jaxb.SuperBook o=new org.apache.cxf.jaxrs.fortest.jaxb.SuperBook();
o.setName("name #" + i);
list.add(o);
}
XmlList xmlList=new XmlList(list);
Method m=XmlListResource.class.getMethod("testJaxb2",new Class[]{});
JAXBContext context=provider.getJAXBContext(m.getReturnType(),m.getGenericReturnType());
ByteArrayOutputStream os=new ByteArrayOutputStream();
context.createMarshaller().marshal(xmlList,os);
@SuppressWarnings("unchecked") XmlList list2=(XmlList)context.createUnmarshaller().unmarshal(new ByteArrayInputStream(os.toByteArray()));
List actualList=list2.getList();
assertEquals(10,actualList.size());
for (int i=0; i < 10; i++) {
org.apache.cxf.jaxrs.fortest.jaxb.SuperBook object=actualList.get(i);
assertEquals("name #" + i,object.getName());
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testExtraClassWithoutSingleContext() throws Exception {
ClassResourceInfo cri=ResourceUtils.createClassResourceInfo(BookStore.class,BookStore.class,true,true);
JAXBElementProvider provider=new JAXBElementProvider();
provider.setExtraClass(new Class[]{SuperBook.class});
provider.init(Collections.singletonList(cri));
JAXBContext bookContext=provider.getJAXBContext(Book.class,Book.class);
ByteArrayOutputStream os=new ByteArrayOutputStream();
bookContext.createMarshaller().marshal(new SuperBook("name",1L,2L),os);
SuperBook book=(SuperBook)bookContext.createUnmarshaller().unmarshal(new ByteArrayInputStream(os.toByteArray()));
assertEquals(2L,book.getSuperId());
}
Class: org.apache.cxf.jaxrs.provider.PrimitiveTextProviderTest InternalCallVerifier EqualityVerifier
@SuppressWarnings("unchecked") @Test public void testReadByte() throws Exception {
MessageBodyReader> p=new PrimitiveTextProvider();
@SuppressWarnings("rawtypes") Byte valueRead=(Byte)p.readFrom((Class)Byte.TYPE,null,null,null,null,new ByteArrayInputStream("1".getBytes()));
assertEquals(1,valueRead.byteValue());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testReadChineeseChars() throws Exception {
String s="䏿–‡";
MessageBodyReader p=new PrimitiveTextProvider();
String value=(String)p.readFrom(String.class,null,new Annotation[]{},MediaType.valueOf(MediaType.APPLICATION_XML + ";charset=UTF-8"),null,new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8)));
assertEquals(value,value);
}
BooleanVerifier InternalCallVerifier
@SuppressWarnings({"unchecked","rawtypes"}) @Test public void testReadBoolean() throws Exception {
MessageBodyReader p=new PrimitiveTextProvider();
boolean valueRead=(Boolean)p.readFrom(Boolean.TYPE,null,null,null,null,new ByteArrayInputStream("true".getBytes()));
assertTrue(valueRead);
}
Class: org.apache.cxf.jaxrs.provider.ProviderFactoryAllTest InternalCallVerifier IdentityVerifier
@Test public void testCustomJsonProvider(){
ProviderFactory pf=ServerProviderFactory.getInstance();
JSONProvider provider=new JSONProvider();
pf.registerUserProvider(provider);
MessageBodyReader> customJsonReader=pf.createMessageBodyReader(Book.class,null,null,MediaType.APPLICATION_JSON_TYPE,new MessageImpl());
assertSame(customJsonReader,provider);
MessageBodyWriter> customJsonWriter=pf.createMessageBodyWriter(Book.class,null,null,MediaType.APPLICATION_JSON_TYPE,new MessageImpl());
assertSame(customJsonWriter,provider);
}
InternalCallVerifier IdentityVerifier
@Test public void testAtomPojoProvider(){
ProviderFactory pf=ServerProviderFactory.getInstance();
AtomPojoProvider provider=new AtomPojoProvider();
pf.registerUserProvider(provider);
MessageBodyReader> feedReader=pf.createMessageBodyReader(Book.class,Book.class,null,MediaType.valueOf("application/atom+xml"),new MessageImpl());
assertSame(feedReader,provider);
MessageBodyReader> entryReader=pf.createMessageBodyReader(TagVO.class,TagVO.class,null,MediaType.valueOf("application/atom+xml;type=entry"),new MessageImpl());
assertSame(entryReader,provider);
}
Class: org.apache.cxf.jaxrs.provider.ProviderFactoryExceptionMapperTest InternalCallVerifier EqualityVerifier
@Test public void testNearestSuperclassMatch(){
ExceptionMapper> exceptionMapper=pf.createExceptionMapper(NullPointerException.class,new MessageImpl());
assertEquals("Wrong mapper found for NullPointerException",RuntimeExceptionMapper.class,exceptionMapper.getClass());
}
InternalCallVerifier EqualityVerifier
@Test public void testExactMatchInSecondPosition(){
ExceptionMapper> exceptionMapper=pf.createExceptionMapper(RuntimeException1.class,new MessageImpl());
assertEquals("Wrong mapper found for RuntimeException1",RuntimeExceptionMapper1.class,exceptionMapper.getClass());
}
InternalCallVerifier EqualityVerifier
@Test public void testExactMatchInFirstPosition(){
ExceptionMapper> exceptionMapper=pf.createExceptionMapper(RuntimeException2.class,new MessageImpl());
assertEquals("Wrong mapper found for RuntimeException2",RuntimeExceptionMapper2.class,exceptionMapper.getClass());
}
Class: org.apache.cxf.jaxrs.provider.ProviderFactoryTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testCustomProviderSorting2(){
ProviderFactory pf=ServerProviderFactory.getInstance();
Comparator comp=new Comparator(){
@Override public int compare( Object provider1, Object provider2){
if (provider1 instanceof StringTextProvider) {
return 1;
}
else if (provider2 instanceof StringTextProvider) {
return -1;
}
else {
return 0;
}
}
}
;
pf.setProviderComparator(comp);
List>> writers=pf.getMessageWriters();
assertEquals(8,writers.size());
Object lastWriter=writers.get(7).getProvider();
assertTrue(lastWriter instanceof StringTextProvider);
List>> readers=pf.getMessageReaders();
assertEquals(8,readers.size());
Object lastReader=readers.get(7).getProvider();
assertTrue(lastReader instanceof StringTextProvider);
}
BooleanVerifier InternalCallVerifier
@Test public void testGetComplexProvider2() throws Exception {
ServerProviderFactory pf=ServerProviderFactory.getInstance();
pf.registerUserProvider(new ComplexMessageBodyReader());
MessageBodyReader reader=pf.createMessageBodyReader(Book.class,Book.class,null,MediaType.APPLICATION_JSON_TYPE,new MessageImpl());
assertTrue(ComplexMessageBodyReader.class == reader.getClass());
}
BooleanVerifier InternalCallVerifier
@Test public void testRegisterCustomResolver() throws Exception {
ProviderFactory pf=ServerProviderFactory.getInstance();
pf.registerUserProvider(new JAXBContextProvider());
Message message=prepareMessage("*/*",null);
ContextResolver cr=pf.createContextResolver(JAXBContext.class,message);
assertFalse(cr instanceof ProviderFactory.ContextResolverProxy);
assertTrue("JAXBContext ContextProvider can not be found",cr instanceof JAXBContextProvider);
}
BooleanVerifier InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testSchemaLocations(){
ProviderFactory pf=ServerProviderFactory.getInstance();
MessageBodyReader jaxbReader=pf.createMessageBodyReader(Book.class,null,null,MediaType.TEXT_XML_TYPE,new MessageImpl());
assertTrue(jaxbReader instanceof JAXBElementProvider);
pf.setSchemaLocations(Collections.singletonList("classpath:/test.xsd"));
MessageBodyReader customJaxbReader=pf.createMessageBodyReader(Book.class,null,null,MediaType.TEXT_XML_TYPE,new MessageImpl());
assertTrue(jaxbReader instanceof JAXBElementProvider);
assertSame(jaxbReader,customJaxbReader);
assertNotNull(((JAXBElementProvider)customJaxbReader).getSchema());
}
BooleanVerifier InternalCallVerifier
@Test public void testExceptionMappersHierarchy4() throws Exception {
Message m=new MessageImpl();
m.put("default.wae.mapper.least.specific",true);
ServerProviderFactory pf=ServerProviderFactory.getInstance();
ExceptionMapper em=pf.createExceptionMapper(WebApplicationException.class,m);
assertTrue(em instanceof WebApplicationExceptionMapper);
}
BooleanVerifier InternalCallVerifier
@Test public void testSortEntityProviders() throws Exception {
ProviderFactory pf=ServerProviderFactory.getInstance();
pf.registerUserProvider(new TestStringProvider());
pf.registerUserProvider(new PrimitiveTextProvider());
List>> readers=pf.getMessageReaders();
assertTrue(indexOf(readers,TestStringProvider.class) < indexOf(readers,PrimitiveTextProvider.class));
List>> writers=pf.getMessageWriters();
assertTrue(indexOf(writers,TestStringProvider.class) < indexOf(writers,PrimitiveTextProvider.class));
}
InternalCallVerifier IdentityVerifier
@Test public void testWebApplicationMapperWithGenerics() throws Exception {
ServerProviderFactory pf=ServerProviderFactory.getInstance();
CustomWebApplicationExceptionMapper mapper=new CustomWebApplicationExceptionMapper();
pf.registerUserProvider(mapper);
Object mapperResponse=pf.createExceptionMapper(WebApplicationException.class,new MessageImpl());
assertSame(mapperResponse,mapper);
}
BooleanVerifier InternalCallVerifier
@Test public void testExceptionMappersHierarchy5() throws Exception {
Message m=new MessageImpl();
ServerProviderFactory pf=ServerProviderFactory.getInstance();
ExceptionMapper em=pf.createExceptionMapper(WebApplicationException.class,m);
assertTrue(em instanceof WebApplicationExceptionMapper);
}
InternalCallVerifier NullVerifier
@Test public void testSetSchemasFromClasspath(){
JAXBElementProvider> provider=new JAXBElementProvider();
ProviderFactory pf=ServerProviderFactory.getInstance();
pf.registerUserProvider(provider);
List locations=new ArrayList();
locations.add("classpath:/test.xsd");
pf.setSchemaLocations(locations);
Schema s=provider.getSchema();
assertNotNull("schema can not be read from classpath",s);
}
InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testExceptionMappersHierarchy1() throws Exception {
ServerProviderFactory pf=ServerProviderFactory.getInstance();
WebApplicationExceptionMapper wm=new WebApplicationExceptionMapper();
pf.registerUserProvider(wm);
assertSame(wm,pf.createExceptionMapper(WebApplicationException.class,new MessageImpl()));
assertNull(pf.createExceptionMapper(RuntimeException.class,new MessageImpl()));
TestRuntimeExceptionMapper rm=new TestRuntimeExceptionMapper();
pf.registerUserProvider(rm);
assertSame(wm,pf.createExceptionMapper(WebApplicationException.class,new MessageImpl()));
assertSame(rm,pf.createExceptionMapper(RuntimeException.class,new MessageImpl()));
}
BooleanVerifier InternalCallVerifier
@Test public void testMessageBodyWriterString() throws Exception {
ProviderFactory pf=ServerProviderFactory.getInstance();
MessageBodyWriter mbr=pf.createMessageBodyWriter(String.class,String.class,new Annotation[]{},MediaType.APPLICATION_XML_TYPE,new MessageImpl());
assertTrue(mbr instanceof StringTextProvider);
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testCustomProviderSortingWithBus(){
WildcardReader wc1=new WildcardReader();
WildcardReader2 wc2=new WildcardReader2();
Bus bus=BusFactory.newInstance().createBus();
bus.setProperty(MessageBodyReader.class.getName(),wc1);
ProviderFactory pf=ServerProviderFactory.createInstance(bus);
pf.registerUserProvider(wc2);
List>> readers=pf.getMessageReaders();
assertEquals(10,readers.size());
assertSame(wc2,readers.get(6).getProvider());
assertSame(wc1,readers.get(7).getProvider());
}
InternalCallVerifier IdentityVerifier
@Test public void testExceptionMappersHierarchy3() throws Exception {
Message m=new MessageImpl();
m.put("default.wae.mapper.least.specific",true);
ServerProviderFactory pf=ServerProviderFactory.getInstance();
TestRuntimeExceptionMapper rm=new TestRuntimeExceptionMapper();
pf.registerUserProvider(rm);
ExceptionMapper em=pf.createExceptionMapper(WebApplicationException.class,m);
assertSame(rm,em);
assertSame(rm,pf.createExceptionMapper(RuntimeException.class,m));
WebApplicationExceptionMapper wm=new WebApplicationExceptionMapper();
pf.registerUserProvider(wm);
assertSame(wm,pf.createExceptionMapper(WebApplicationException.class,m));
assertSame(rm,pf.createExceptionMapper(RuntimeException.class,m));
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testComplexExceptionMapper(){
ServerProviderFactory pf=ServerProviderFactory.getInstance();
pf.registerUserProvider(new SecurityExceptionMapper());
ExceptionMapper mapper=pf.createExceptionMapper(SecurityException.class,new MessageImpl());
assertTrue(mapper instanceof SecurityExceptionMapper);
ExceptionMapper mapper2=pf.createExceptionMapper(Throwable.class,new MessageImpl());
assertNull(mapper2);
}
BooleanVerifier InternalCallVerifier IdentityVerifier HybridVerifier
@Test public void testExceptionMappersHierarchy2() throws Exception {
ServerProviderFactory pf=ServerProviderFactory.getInstance();
TestRuntimeExceptionMapper rm=new TestRuntimeExceptionMapper();
pf.registerUserProvider(rm);
ExceptionMapper em=pf.createExceptionMapper(WebApplicationException.class,new MessageImpl());
assertTrue(em instanceof WebApplicationExceptionMapper);
assertSame(rm,pf.createExceptionMapper(RuntimeException.class,new MessageImpl()));
WebApplicationExceptionMapper wm=new WebApplicationExceptionMapper();
pf.registerUserProvider(wm);
assertSame(wm,pf.createExceptionMapper(WebApplicationException.class,new MessageImpl()));
assertSame(rm,pf.createExceptionMapper(RuntimeException.class,new MessageImpl()));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testCustomProviderSorting(){
ProviderFactory pf=ServerProviderFactory.getInstance();
Comparator> comp=new Comparator>(){
@Override public int compare( ProviderInfo> o1, ProviderInfo> o2){
Object provider1=o1.getProvider();
Object provider2=o2.getProvider();
if (provider1 instanceof StringTextProvider) {
return 1;
}
else if (provider2 instanceof StringTextProvider) {
return -1;
}
else {
return 0;
}
}
}
;
pf.setProviderComparator(comp);
List>> writers=pf.getMessageWriters();
assertEquals(8,writers.size());
Object lastWriter=writers.get(7).getProvider();
assertTrue(lastWriter instanceof StringTextProvider);
List>> readers=pf.getMessageReaders();
assertEquals(8,readers.size());
Object lastReader=readers.get(7).getProvider();
assertTrue(lastReader instanceof StringTextProvider);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@SuppressWarnings("rawtypes") @Test public void testCustomProviderSortingMBROnly(){
ProviderFactory pf=ServerProviderFactory.getInstance();
Comparator> comp=new Comparator>(){
@Override public int compare( ProviderInfo o1, ProviderInfo o2){
MessageBodyReader> provider1=o1.getProvider();
MessageBodyReader> provider2=o2.getProvider();
if (provider1 instanceof StringTextProvider) {
return 1;
}
else if (provider2 instanceof StringTextProvider) {
return -1;
}
else {
return 0;
}
}
}
;
pf.setProviderComparator(comp);
List>> writers=pf.getMessageWriters();
assertEquals(8,writers.size());
Object lastWriter=writers.get(7).getProvider();
assertFalse(lastWriter instanceof StringTextProvider);
List>> readers=pf.getMessageReaders();
assertEquals(8,readers.size());
Object lastReader=readers.get(7).getProvider();
assertTrue(lastReader instanceof StringTextProvider);
}
InternalCallVerifier IdentityVerifier
@Test public void testExceptionMappersHierarchyWithGenerics() throws Exception {
ServerProviderFactory pf=ServerProviderFactory.getInstance();
RuntimeExceptionMapper1 exMapper1=new RuntimeExceptionMapper1();
pf.registerUserProvider(exMapper1);
RuntimeExceptionMapper2 exMapper2=new RuntimeExceptionMapper2();
pf.registerUserProvider(exMapper2);
assertSame(exMapper1,pf.createExceptionMapper(RuntimeException.class,new MessageImpl()));
Object webExMapper=pf.createExceptionMapper(WebApplicationException.class,new MessageImpl());
assertSame(exMapper2,webExMapper);
}
BooleanVerifier InternalCallVerifier IdentityVerifier HybridVerifier
@Test public void testDataSourceReader(){
ProviderFactory pf=ServerProviderFactory.getInstance();
pf.registerUserProvider(new DataSourceProvider());
MessageBodyReader reader=pf.createMessageBodyReader(DataSource.class,null,null,MediaType.valueOf("image/png"),new MessageImpl());
assertTrue(reader instanceof DataSourceProvider);
MessageBodyReader reader2=pf.createMessageBodyReader(DataHandler.class,null,null,MediaType.valueOf("image/png"),new MessageImpl());
assertSame(reader,reader2);
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testCustomProviderSortingWithBus2(){
WildcardReader wc1=new WildcardReader();
WildcardReader2 wc2=new WildcardReader2();
Bus bus=BusFactory.newInstance().createBus();
bus.setProperty(MessageBodyReader.class.getName(),wc2);
ProviderFactory pf=ServerProviderFactory.createInstance(bus);
pf.registerUserProvider(wc1);
List>> readers=pf.getMessageReaders();
assertEquals(10,readers.size());
assertSame(wc1,readers.get(6).getProvider());
assertSame(wc2,readers.get(7).getProvider());
}
BooleanVerifier InternalCallVerifier
@Test public void testMessageBodyReaderBoolean() throws Exception {
ProviderFactory pf=ServerProviderFactory.getInstance();
pf.registerUserProvider(new CustomBooleanReader());
MessageBodyReader mbr=pf.createMessageBodyReader(Boolean.class,Boolean.class,new Annotation[]{},MediaType.TEXT_PLAIN_TYPE,new MessageImpl());
assertTrue(mbr instanceof PrimitiveTextProvider);
}
BooleanVerifier InternalCallVerifier
@Test public void testGetComplexProvider() throws Exception {
ServerProviderFactory pf=ServerProviderFactory.getInstance();
pf.registerUserProvider(new ComplexMessageBodyReader());
Message m=new MessageImpl();
Exchange ex=new ExchangeImpl();
m.setExchange(ex);
m.put(ServerProviderFactory.IGNORE_TYPE_VARIABLES,true);
MessageBodyReader reader=pf.createMessageBodyReader(Book.class,Book.class,null,MediaType.APPLICATION_JSON_TYPE,m);
assertTrue(ComplexMessageBodyReader.class == reader.getClass());
}
InternalCallVerifier IdentityVerifier
@Test public void testGoodExceptionMappersHierarchyWithGenerics() throws Exception {
ServerProviderFactory pf=ServerProviderFactory.getInstance();
GoodRuntimeExceptionAMapper runtimeExceptionAMapper=new GoodRuntimeExceptionAMapper();
pf.registerUserProvider(runtimeExceptionAMapper);
GoodRuntimeExceptionBMapper runtimeExceptionBMapper=new GoodRuntimeExceptionBMapper();
pf.registerUserProvider(runtimeExceptionBMapper);
Object mapperResponse1=pf.createExceptionMapper(RuntimeExceptionA.class,new MessageImpl());
assertSame(runtimeExceptionAMapper,mapperResponse1);
Object mapperResponse2=pf.createExceptionMapper(RuntimeExceptionB.class,new MessageImpl());
assertSame(runtimeExceptionBMapper,mapperResponse2);
Object mapperResponse3=pf.createExceptionMapper(RuntimeExceptionAA.class,new MessageImpl());
assertSame(runtimeExceptionAMapper,mapperResponse3);
Object mapperResponse4=pf.createExceptionMapper(RuntimeExceptionBB.class,new MessageImpl());
assertSame(runtimeExceptionBMapper,mapperResponse4);
}
InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testOrderOfProvidersWithSameProperties(){
ProviderFactory pf=ServerProviderFactory.getInstance();
WildcardReader reader1=new WildcardReader();
pf.registerUserProvider(reader1);
WildcardReader2 reader2=new WildcardReader2();
pf.registerUserProvider(reader2);
List>> readers=pf.getMessageReaders();
assertEquals(10,readers.size());
assertSame(reader1,readers.get(6).getProvider());
assertSame(reader2,readers.get(7).getProvider());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testCustomProviderSortingMBWOnly(){
ProviderFactory pf=ServerProviderFactory.getInstance();
Comparator>> comp=new Comparator>>(){
@Override public int compare( ProviderInfo> o1, ProviderInfo> o2){
MessageBodyWriter> provider1=o1.getProvider();
MessageBodyWriter> provider2=o2.getProvider();
if (provider1 instanceof StringTextProvider) {
return 1;
}
else if (provider2 instanceof StringTextProvider) {
return -1;
}
else {
return 0;
}
}
}
;
pf.setProviderComparator(comp);
List>> writers=pf.getMessageWriters();
assertEquals(8,writers.size());
Object lastWriter=writers.get(7).getProvider();
assertTrue(lastWriter instanceof StringTextProvider);
List>> readers=pf.getMessageReaders();
assertEquals(8,readers.size());
Object lastReader=readers.get(7).getProvider();
assertFalse(lastReader instanceof StringTextProvider);
}
InternalCallVerifier IdentityVerifier
@Test public void testBadCustomExceptionMappersHierarchyWithGenerics() throws Exception {
ServerProviderFactory pf=ServerProviderFactory.getInstance();
BadExceptionMapperA badExceptionMapperA=new BadExceptionMapperA();
pf.registerUserProvider(badExceptionMapperA);
BadExceptionMapperB badExceptionMapperB=new BadExceptionMapperB();
pf.registerUserProvider(badExceptionMapperB);
Object mapperResponse1=pf.createExceptionMapper(RuntimeExceptionA.class,new MessageImpl());
assertSame(badExceptionMapperA,mapperResponse1);
Object mapperResponse2=pf.createExceptionMapper(RuntimeExceptionB.class,new MessageImpl());
assertSame(badExceptionMapperB,mapperResponse2);
Object mapperResponse3=pf.createExceptionMapper(RuntimeExceptionAA.class,new MessageImpl());
assertSame(badExceptionMapperA,mapperResponse3);
Object mapperResponse4=pf.createExceptionMapper(RuntimeExceptionBB.class,new MessageImpl());
assertSame(badExceptionMapperB,mapperResponse4);
}
InternalCallVerifier IdentityVerifier
@Test public void testGetFactoryInboundMessage(){
ProviderFactory factory=ServerProviderFactory.getInstance();
Message m=new MessageImpl();
Exchange e=new ExchangeImpl();
m.setExchange(e);
Endpoint endpoint=EasyMock.createMock(Endpoint.class);
endpoint.get(ServerProviderFactory.class.getName());
EasyMock.expectLastCall().andReturn(factory);
EasyMock.replay(endpoint);
e.put(Endpoint.class,endpoint);
assertSame(ProviderFactory.getInstance(m),factory);
}
BooleanVerifier InternalCallVerifier
@Test public void testMessageBodyReaderString() throws Exception {
ProviderFactory pf=ServerProviderFactory.getInstance();
MessageBodyReader mbr=pf.createMessageBodyReader(String.class,String.class,new Annotation[]{},MediaType.APPLICATION_XML_TYPE,new MessageImpl());
assertTrue(mbr instanceof StringTextProvider);
}
InternalCallVerifier IdentityVerifier
@Test public void testMessageBodyHandlerHierarchy() throws Exception {
ProviderFactory pf=ServerProviderFactory.getInstance();
List providers=new ArrayList();
BookReaderWriter bookHandler=new BookReaderWriter();
providers.add(bookHandler);
SuperBookReaderWriter superBookHandler=new SuperBookReaderWriter();
providers.add(superBookHandler);
pf.setUserProviders(providers);
assertSame(bookHandler,pf.createMessageBodyReader(Book.class,Book.class,new Annotation[]{},MediaType.APPLICATION_XML_TYPE,new MessageImpl()));
assertSame(superBookHandler,pf.createMessageBodyReader(SuperBook.class,SuperBook.class,new Annotation[]{},MediaType.APPLICATION_XML_TYPE,new MessageImpl()));
assertSame(bookHandler,pf.createMessageBodyWriter(Book.class,Book.class,new Annotation[]{},MediaType.APPLICATION_XML_TYPE,new MessageImpl()));
assertSame(superBookHandler,pf.createMessageBodyWriter(SuperBook.class,SuperBook.class,new Annotation[]{},MediaType.APPLICATION_XML_TYPE,new MessageImpl()));
}
BooleanVerifier InternalCallVerifier IdentityVerifier HybridVerifier
@Test public void testDataSourceWriter(){
ProviderFactory pf=ServerProviderFactory.getInstance();
pf.registerUserProvider(new DataSourceProvider());
MessageBodyWriter writer=pf.createMessageBodyWriter(DataSource.class,null,null,MediaType.valueOf("image/png"),new MessageImpl());
assertTrue(writer instanceof DataSourceProvider);
MessageBodyWriter writer2=pf.createMessageBodyWriter(DataHandler.class,null,null,MediaType.valueOf("image/png"),new MessageImpl());
assertSame(writer,writer2);
}
InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testDefaultUserExceptionMappers() throws Exception {
ServerProviderFactory pf=ServerProviderFactory.getInstance();
ExceptionMapper> mapper=pf.createExceptionMapper(WebApplicationException.class,new MessageImpl());
assertNotNull(mapper);
WebApplicationExceptionMapper wm=new WebApplicationExceptionMapper();
pf.registerUserProvider(wm);
ExceptionMapper> mapper2=pf.createExceptionMapper(WebApplicationException.class,new MessageImpl());
assertNotSame(mapper,mapper2);
assertSame(wm,mapper2);
}
InternalCallVerifier NullVerifier
@Test public void testNoCustomResolver() throws Exception {
ProviderFactory pf=ServerProviderFactory.getInstance();
pf.registerUserProvider(new JAXBContextProvider());
pf.registerUserProvider(new JAXBContextProvider2());
Message message=prepareMessage("text/xml+c",null);
ContextResolver cr=pf.createContextResolver(JAXBContext.class,message);
assertNull(cr);
}
InternalCallVerifier IdentityVerifier
@Test public void testCustomJaxbProvider(){
ProviderFactory pf=ServerProviderFactory.getInstance();
JAXBElementProvider provider=new JAXBElementProvider();
pf.registerUserProvider(provider);
MessageBodyReader customJaxbReader=pf.createMessageBodyReader(Book.class,null,null,MediaType.TEXT_XML_TYPE,new MessageImpl());
assertSame(customJaxbReader,provider);
MessageBodyWriter customJaxbWriter=pf.createMessageBodyWriter(Book.class,null,null,MediaType.TEXT_XML_TYPE,new MessageImpl());
assertSame(customJaxbWriter,provider);
}
BooleanVerifier InternalCallVerifier
@Test public void testRegisterCustomResolver2() throws Exception {
ProviderFactory pf=ServerProviderFactory.getInstance();
pf.registerUserProvider(new JAXBContextProvider());
pf.registerUserProvider(new JAXBContextProvider2());
Message message=prepareMessage("text/xml+b",null);
ContextResolver cr=pf.createContextResolver(JAXBContext.class,message);
assertFalse(cr instanceof ProviderFactory.ContextResolverProxy);
assertTrue("JAXBContext ContextProvider can not be found",cr instanceof JAXBContextProvider2);
}
InternalCallVerifier IdentityVerifier
@Test public void testMessageBodyWriterNoTypes() throws Exception {
ProviderFactory pf=ServerProviderFactory.getInstance();
List providers=new ArrayList();
SuperBookReaderWriter2 superBookHandler=new SuperBookReaderWriter2();
providers.add(superBookHandler);
pf.setUserProviders(providers);
assertSame(superBookHandler,pf.createMessageBodyReader(SuperBook.class,SuperBook.class,new Annotation[]{},MediaType.APPLICATION_XML_TYPE,new MessageImpl()));
assertSame(superBookHandler,pf.createMessageBodyWriter(SuperBook.class,SuperBook.class,new Annotation[]{},MediaType.APPLICATION_XML_TYPE,new MessageImpl()));
}
BooleanVerifier InternalCallVerifier
@Test public void testMessageBodyReaderBoolean2() throws Exception {
ProviderFactory pf=ServerProviderFactory.getInstance();
pf.registerUserProvider(new CustomBooleanReader2());
MessageBodyReader mbr=pf.createMessageBodyReader(Boolean.class,Boolean.class,new Annotation[]{},MediaType.TEXT_PLAIN_TYPE,new MessageImpl());
assertTrue(mbr instanceof CustomBooleanReader2);
}
InternalCallVerifier IdentityVerifier
@Test public void testParameterHandlerProvider() throws Exception {
ProviderFactory pf=ServerProviderFactory.getInstance();
ParamConverterProvider h=new CustomerParameterHandler();
pf.registerUserProvider(h);
ParamConverter h2=pf.createParameterHandler(Customer.class,Customer.class,null,new MessageImpl());
assertSame(h2,h);
}
BooleanVerifier InternalCallVerifier
@Test public void testCustomResolverProxy() throws Exception {
ProviderFactory pf=ServerProviderFactory.getInstance();
pf.registerUserProvider(new JAXBContextProvider());
pf.registerUserProvider(new JAXBContextProvider2());
Message message=prepareMessage("text/xml+*",null);
ContextResolver cr=pf.createContextResolver(JAXBContext.class,message);
assertTrue(cr instanceof ProviderFactory.ContextResolverProxy);
assertTrue(((ProviderFactory.ContextResolverProxy>)cr).getResolvers().get(0) instanceof JAXBContextProvider);
assertTrue(((ProviderFactory.ContextResolverProxy>)cr).getResolvers().get(1) instanceof JAXBContextProvider2);
}
Class: org.apache.cxf.jaxrs.provider.RequestDispatcherProviderTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testIsWriteableEnum2(){
RequestDispatcherProvider p=new RequestDispatcherProvider();
p.setEnumResources(Collections.singletonMap(TestEnum.ONE,"/test.jsp"));
assertTrue(p.isWriteable(TestEnum.ONE.getClass(),null,null,null));
assertEquals("/test.jsp",p.getResourcePath(TestEnum.ONE.getClass(),TestEnum.ONE));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testIsWriteableEnum(){
RequestDispatcherProvider p=new RequestDispatcherProvider();
p.setClassResources(Collections.singletonMap(TestEnum.class.getName() + "." + TestEnum.ONE,"/test.jsp"));
assertTrue(p.isWriteable(TestEnum.ONE.getClass(),null,null,null));
assertEquals("/test.jsp",p.getResourcePath(TestEnum.ONE.getClass(),TestEnum.ONE));
}
Class: org.apache.cxf.jaxrs.provider.SourceProviderTest InternalCallVerifier IdentityVerifier
@Test public void testReadFromWithPreferredFormat() throws Exception {
TestSourceProvider p=new TestSourceProvider();
p.getMessage().put("source-preferred-format","sax");
assertSame(StaxSource.class,verifyRead(p,Source.class).getClass());
}
Class: org.apache.cxf.jaxrs.provider.XPathProviderTest BooleanVerifier InternalCallVerifier
@Test public void testIsReadableClassNames(){
XPathProvider> provider=new XPathProvider();
assertFalse(provider.isReadable(Book.class,null,null,null));
assertFalse(provider.isReadable(BookStore.class,null,null,null));
Map map=new HashMap();
map.put(Book.class.getName(),"/");
provider.setExpressions(map);
assertFalse(provider.isReadable(BookStore.class,null,null,null));
assertTrue(provider.isReadable(Book.class,null,null,null));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testReadFrom() throws Exception {
String value="The Book 2 ";
XPathProvider provider=new XPathProvider();
provider.setExpression("/Book");
provider.setClassName(Book.class.getName());
provider.setForceDOM(true);
Book book=(Book)provider.readFrom(Book.class,null,null,null,null,new ByteArrayInputStream(value.getBytes()));
assertNotNull(book);
assertEquals(2L,book.getId());
assertEquals("The Book",book.getName());
}
BooleanVerifier InternalCallVerifier
@Test public void testIsReadableClassName(){
XPathProvider> provider=new XPathProvider();
provider.setExpression("/");
assertTrue(provider.isReadable(Book.class,null,null,null));
assertTrue(provider.isReadable(BookStore.class,null,null,null));
provider.setClassName(Book.class.getName());
assertFalse(provider.isReadable(BookStore.class,null,null,null));
assertTrue(provider.isReadable(Book.class,null,null,null));
provider.setClassName(null);
assertTrue(provider.isReadable(Book.class,null,null,null));
assertTrue(provider.isReadable(BookStore.class,null,null,null));
}
Class: org.apache.cxf.jaxrs.provider.XSLTJaxbProviderTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testWriteWithoutTemplate() throws Exception {
XSLTJaxbProvider provider=new XSLTJaxbProvider();
provider.setSupportJaxbOnly(true);
Book b=new Book();
b.setId(123L);
b.setName("TheBook");
ByteArrayOutputStream bos=new ByteArrayOutputStream();
provider.writeTo(b,Book.class,Book.class,b.getClass().getAnnotations(),MediaType.TEXT_XML_TYPE,new MetadataMap(),bos);
Unmarshaller um=provider.getClassContext(Book.class).createUnmarshaller();
Book b2=(Book)um.unmarshal(new StringReader(bos.toString()));
assertEquals(b,b2);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testReadWithoutTemplate() throws Exception {
XSLTJaxbProvider provider=new XSLTJaxbProvider();
provider.setSupportJaxbOnly(true);
Book b=new Book();
b.setId(123L);
b.setName("TheBook");
Book b2=provider.readFrom(Book.class,Book.class,b.getClass().getAnnotations(),MediaType.TEXT_XML_TYPE,new MetadataMap(),new ByteArrayInputStream(BOOK_XML.getBytes()));
assertEquals("Transformation is bad",b,b2);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testWrite() throws Exception {
XSLTJaxbProvider provider=new XSLTJaxbProvider();
provider.setOutTemplate(TEMPLATE_LOCATION);
provider.setMessageContext(new MessageContextImpl(createMessage()));
Book b=new Book();
b.setId(123L);
b.setName("TheBook");
ByteArrayOutputStream bos=new ByteArrayOutputStream();
provider.writeTo(b,Book.class,Book.class,b.getClass().getAnnotations(),MediaType.TEXT_XML_TYPE,new MetadataMap(),bos);
Unmarshaller um=provider.getClassContext(Book.class).createUnmarshaller();
Book b2=(Book)um.unmarshal(new StringReader(bos.toString()));
b.setName("TheBook2");
assertEquals("Transformation is bad",b,b2);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testWriteToStreamWriter() throws Exception {
XSLTJaxbProvider provider=new XSLTJaxbProvider(){
@Override protected XMLStreamWriter getStreamWriter( Object obj, OutputStream os, MediaType mt){
return StaxUtils.createXMLStreamWriter(os);
}
}
;
provider.setOutTemplate(TEMPLATE_LOCATION);
provider.setMessageContext(new MessageContextImpl(createMessage()));
Book b=new Book();
b.setId(123L);
b.setName("TheBook");
ByteArrayOutputStream bos=new ByteArrayOutputStream();
provider.writeTo(b,Book.class,Book.class,b.getClass().getAnnotations(),MediaType.TEXT_XML_TYPE,new MetadataMap(),bos);
Unmarshaller um=provider.getClassContext(Book.class).createUnmarshaller();
Book b2=(Book)um.unmarshal(new StringReader(bos.toString()));
b.setName("TheBook2");
assertEquals("Transformation is bad",b,b2);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testRead() throws Exception {
XSLTJaxbProvider provider=new XSLTJaxbProvider();
provider.setInTemplate(TEMPLATE_LOCATION);
Book b=new Book();
b.setId(123L);
b.setName("TheBook");
Book b2=provider.readFrom(Book.class,Book.class,b.getClass().getAnnotations(),MediaType.TEXT_XML_TYPE,new MetadataMap(),new ByteArrayInputStream(BOOK_XML.getBytes()));
b.setName("TheBook2");
assertEquals("Transformation is bad",b,b2);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testReadFromStreamReader() throws Exception {
XSLTJaxbProvider provider=new XSLTJaxbProvider(){
@Override protected XMLStreamReader getStreamReader( InputStream is, Class> type, MediaType mt){
return StaxUtils.createXMLStreamReader(is);
}
}
;
provider.setInTemplate(TEMPLATE_LOCATION);
Book b=new Book();
b.setId(123L);
b.setName("TheBook");
Book b2=provider.readFrom(Book.class,Book.class,b.getClass().getAnnotations(),MediaType.TEXT_XML_TYPE,new MetadataMap(),new ByteArrayInputStream(BOOK_XML.getBytes()));
b.setName("TheBook2");
assertEquals("Transformation is bad",b,b2);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testWriteWithAnnotation() throws Exception {
XSLTJaxbProvider provider=new XSLTJaxbProvider();
provider.setMessageContext(new MessageContextImpl(createMessage()));
Book b=new Book();
b.setId(123L);
b.setName("TheBook");
ByteArrayOutputStream bos=new ByteArrayOutputStream();
Annotation[] anns=Root.class.getMethod("getBook").getAnnotations();
assertTrue(provider.isWriteable(Book.class,Book.class,anns,MediaType.TEXT_XML_TYPE));
provider.writeTo(b,Book.class,Book.class,anns,MediaType.TEXT_XML_TYPE,new MetadataMap(),bos);
Unmarshaller um=provider.getClassContext(Book.class).createUnmarshaller();
Book b2=(Book)um.unmarshal(new StringReader(bos.toString()));
b.setName("TheBook2");
assertEquals("Transformation is bad",b,b2);
}
Class: org.apache.cxf.jaxrs.provider.aegis.AegisElementProviderTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testNoNamespaceReadFrom() throws Exception {
MessageBodyReader p=new NoNamespaceAegisElementProvider();
byte[] bytes=noNamespaceXml.getBytes("utf-8");
AegisTestBean bean=p.readFrom(AegisTestBean.class,null,null,null,null,new ByteArrayInputStream(bytes));
assertEquals("hovercraft",bean.getStrValue());
assertEquals(Boolean.TRUE,bean.getBoolValue());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testReadFrom() throws Exception {
MessageBodyReader p=new AegisElementProvider();
byte[] simpleBytes=simpleBeanXml.getBytes("utf-8");
AegisTestBean bean=p.readFrom(AegisTestBean.class,null,null,null,null,new ByteArrayInputStream(simpleBytes));
assertEquals("hovercraft",bean.getStrValue());
assertEquals(Boolean.TRUE,bean.getBoolValue());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testReadWriteComplexMap() throws Exception {
Map testMap=new HashMap();
Class iwithMapClass=InterfaceWithMap.class;
Method method=iwithMapClass.getMethod("mapFunction");
Type mapType=method.getGenericReturnType();
AegisTestBean bean=new AegisTestBean();
bean.setBoolValue(Boolean.TRUE);
bean.setStrValue("hovercraft");
AegisSuperBean bean2=new AegisSuperBean();
bean2.setBoolValue(Boolean.TRUE);
bean2.setStrValue("hovercraft2");
testMap.put(bean,bean2);
MessageBodyWriter> writer=new AegisElementProvider>();
ByteArrayOutputStream os=new ByteArrayOutputStream();
writer.writeTo(testMap,testMap.getClass(),mapType,new Annotation[]{},MediaType.APPLICATION_OCTET_STREAM_TYPE,new MetadataMap(),os);
byte[] bytes=os.toByteArray();
String xml=new String(bytes,"utf-8");
MessageBodyReader> reader=new AegisElementProvider>();
byte[] simpleBytes=xml.getBytes("utf-8");
Map map2=reader.readFrom(null,mapType,new Annotation[]{},MediaType.APPLICATION_OCTET_STREAM_TYPE,new MetadataMap(),new ByteArrayInputStream(simpleBytes));
assertEquals(1,map2.size());
Map.Entry entry=map2.entrySet().iterator().next();
AegisTestBean bean1=entry.getKey();
assertEquals("hovercraft",bean1.getStrValue());
assertEquals(Boolean.TRUE,bean1.getBoolValue());
AegisTestBean bean22=entry.getValue();
assertEquals("hovercraft2",bean22.getStrValue());
assertEquals(Boolean.TRUE,bean22.getBoolValue());
}
Class: org.apache.cxf.jaxrs.provider.aegis.AegisJSONProviderTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testReadCollection() throws Exception {
String json=writeCollection(true,false,null,true,false);
byte[] simpleBytes=json.getBytes("utf-8");
Method m=CollectionsResource.class.getMethod("getAegisBeans",new Class[]{});
AegisJSONProvider> p=new AegisJSONProvider>();
List list=p.readFrom(null,m.getGenericReturnType(),null,null,null,new ByteArrayInputStream(simpleBytes));
assertEquals(2,list.size());
AegisTestBean bean=list.get(0);
assertEquals("hovercraft",bean.getStrValue());
assertEquals(Boolean.TRUE,bean.getBoolValue());
bean=list.get(1);
assertEquals("hovercraft2",bean.getStrValue());
assertEquals(Boolean.TRUE,bean.getBoolValue());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@org.junit.Ignore @Test public void testReadWriteComplexMap() throws Exception {
Map testMap=new HashMap();
Class iwithMapClass=InterfaceWithMap.class;
Method method=iwithMapClass.getMethod("mapFunction");
Type mapType=method.getGenericReturnType();
AegisTestBean bean=new AegisTestBean();
bean.setBoolValue(Boolean.TRUE);
bean.setStrValue("hovercraft");
AegisSuperBean bean2=new AegisSuperBean();
bean2.setBoolValue(Boolean.TRUE);
bean2.setStrValue("hovercraft2");
testMap.put(bean,bean2);
AegisJSONProvider> writer=new AegisJSONProvider>();
ByteArrayOutputStream os=new ByteArrayOutputStream();
writer.writeTo(testMap,testMap.getClass(),mapType,null,null,null,os);
byte[] bytes=os.toByteArray();
String xml=new String(bytes,"utf-8");
String expected=properties.getProperty("testReadWriteComplexMap.expected");
assertEquals(expected,xml);
AegisJSONProvider> reader=new AegisJSONProvider>();
byte[] simpleBytes=xml.getBytes("utf-8");
Map map2=reader.readFrom(null,mapType,null,null,null,new ByteArrayInputStream(simpleBytes));
assertEquals(1,map2.size());
Map.Entry entry=map2.entrySet().iterator().next();
AegisTestBean bean1=entry.getKey();
assertEquals("hovercraft",bean1.getStrValue());
assertEquals(Boolean.TRUE,bean1.getBoolValue());
AegisTestBean bean22=entry.getValue();
assertEquals("hovercraft2",bean22.getStrValue());
assertEquals(Boolean.TRUE,bean22.getBoolValue());
}
Class: org.apache.cxf.jaxrs.provider.atom.AtomEntryProviderTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testAnnotations(){
String[] values=afd.getClass().getAnnotation(Produces.class).value();
assertEquals("3 types can be produced",3,values.length);
assertTrue("application/atom+xml".equals(values[0]) && "application/atom+xml;type=entry".equals(values[1]) && "application/json".equals(values[2]));
values=afd.getClass().getAnnotation(Consumes.class).value();
assertEquals("2 types can be consumed",2,values.length);
assertTrue("application/atom+xml".equals(values[0]) && "application/atom+xml;type=entry".equals(values[1]));
}
InternalCallVerifier EqualityVerifier
@Test public void testReadFrom() throws Exception {
InputStream is=getClass().getResourceAsStream("atomEntry.xml");
Entry simple=afd.readFrom(Entry.class,null,null,null,null,is);
assertEquals("Wrong entry title","Atom-Powered Robots Run Amok",simple.getTitle());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testWriteTo() throws Exception {
InputStream is=getClass().getResourceAsStream("atomEntry.xml");
Entry simple=afd.readFrom(Entry.class,null,null,MediaType.valueOf("application/atom+xml;type=entry"),null,is);
ByteArrayOutputStream bos=new ByteArrayOutputStream();
afd.writeTo(simple,null,null,null,MediaType.valueOf("application/atom+xml;type=entry"),null,bos);
ByteArrayInputStream bis=new ByteArrayInputStream(bos.toByteArray());
Entry simpleCopy=afd.readFrom(Entry.class,null,null,MediaType.valueOf("application/atom+xml"),null,bis);
assertEquals("Wrong entry title","Atom-Powered Robots Run Amok",simpleCopy.getTitle());
assertEquals("Wrong entry title",simple.getTitle(),simpleCopy.getTitle());
}
BooleanVerifier InternalCallVerifier
@Test public void testWriteable(){
assertTrue(afd.isWriteable(Entry.class,null,null,null));
assertTrue(afd.isWriteable(FOMEntry.class,null,null,null));
assertFalse(afd.isWriteable(Feed.class,null,null,null));
}
BooleanVerifier InternalCallVerifier
@Test public void testReadable(){
assertTrue(afd.isReadable(Entry.class,null,null,null));
assertTrue(afd.isReadable(FOMEntry.class,null,null,null));
assertFalse(afd.isReadable(Feed.class,null,null,null));
}
Class: org.apache.cxf.jaxrs.provider.atom.AtomFeedProviderTest BooleanVerifier InternalCallVerifier
@Test public void testReadable(){
assertTrue(afd.isReadable(Feed.class,null,null,null));
assertTrue(afd.isReadable(FOMFeed.class,null,null,null));
assertFalse(afd.isReadable(Entry.class,null,null,null));
}
BooleanVerifier InternalCallVerifier
@Test public void testWriteable(){
assertTrue(afd.isWriteable(Feed.class,null,null,null));
assertTrue(afd.isWriteable(FOMFeed.class,null,null,null));
assertFalse(afd.isWriteable(Entry.class,null,null,null));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testAnnotations(){
String[] values=afd.getClass().getAnnotation(Produces.class).value();
assertEquals("3 types can be produced",3,values.length);
assertTrue("application/atom+xml".equals(values[0]) && "application/atom+xml;type=feed".equals(values[1]) && "application/json".equals(values[2]));
values=afd.getClass().getAnnotation(Consumes.class).value();
assertEquals("2 types can be consumed",2,values.length);
assertTrue("application/atom+xml".equals(values[0]) && "application/atom+xml;type=feed".equals(values[1]));
}
InternalCallVerifier EqualityVerifier
@Test public void testReadFrom() throws Exception {
InputStream is=getClass().getResourceAsStream("atomFeed.xml");
Feed simple=afd.readFrom(Feed.class,null,null,null,null,is);
assertEquals("Wrong feed title","Example Feed",simple.getTitle());
}
Class: org.apache.cxf.jaxrs.provider.atom.AtomPojoProviderTest InternalCallVerifier NullVerifier
@Test public void testReadEntryWithBuilders() throws Exception {
AtomPojoProvider provider=(AtomPojoProvider)ctx.getBean("atom3");
assertNotNull(provider);
doTestReadEntry(provider);
}
InternalCallVerifier NullVerifier
@Test public void testWriteEntryWithBuilders() throws Exception {
AtomPojoProvider provider=(AtomPojoProvider)ctx.getBean("atom2");
assertNotNull(provider);
provider.setFormattedOutput(true);
ByteArrayOutputStream bos=new ByteArrayOutputStream();
provider.writeTo(new Book("a"),Book.class,Book.class,new Annotation[]{},MediaType.valueOf("application/atom+xml;type=entry"),null,bos);
ByteArrayInputStream bis=new ByteArrayInputStream(bos.toByteArray());
Entry entry=new AtomEntryProvider().readFrom(Entry.class,null,null,null,null,bis);
verifyEntry(entry,"a");
}
InternalCallVerifier NullVerifier
@Test public void testReadFeedWithBuilders() throws Exception {
AtomPojoProvider provider=(AtomPojoProvider)ctx.getBean("atom4");
assertNotNull(provider);
doTestReadFeed(provider);
}
APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testReadEntryNoContent() throws Exception {
final String entryNoContent="\n" + "\n" + " 84297856 \n"+ " ";
AtomPojoProvider atomPojoProvider=new AtomPojoProvider();
@SuppressWarnings({"rawtypes","unchecked"}) JaxbDataType type=(JaxbDataType)atomPojoProvider.readFrom((Class)JaxbDataType.class,JaxbDataType.class,new Annotation[0],MediaType.valueOf("application/atom+xml;type=entry"),new MetadataMap(),new ByteArrayInputStream(entryNoContent.getBytes(StandardCharsets.UTF_8)));
assertNull(type);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testWriteFeedWithBuildersNoJaxb() throws Exception {
AtomPojoProvider provider=(AtomPojoProvider)ctx.getBean("atomNoJaxb");
assertNotNull(provider);
provider.setFormattedOutput(true);
ByteArrayOutputStream bos=new ByteArrayOutputStream();
Books books=new Books();
List bs=new ArrayList();
bs.add(new Book("a"));
bs.add(new Book("b"));
books.setBooks(bs);
provider.writeTo(books,Books.class,Books.class,new Annotation[]{},MediaType.valueOf("application/atom+xml"),null,bos);
ByteArrayInputStream bis=new ByteArrayInputStream(bos.toByteArray());
Feed feed=new AtomFeedProvider().readFrom(Feed.class,null,null,null,null,bis);
assertEquals("Books",feed.getTitle());
List entries=feed.getEntries();
assertEquals(2,entries.size());
Entry entryA=getEntry(entries,"a");
verifyEntry(entryA,"a");
String entryAContent=entryA.getContent();
assertTrue(" ".equals(entryAContent) || " ".equals(entryAContent) || "".equals(entryAContent));
Entry entryB=getEntry(entries,"b");
verifyEntry(entryB,"b");
String entryBContent=entryB.getContent();
assertTrue(" ".equals(entryBContent) || " ".equals(entryBContent) || "".equals(entryBContent));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testWriteFeedWithBuilders() throws Exception {
AtomPojoProvider provider=(AtomPojoProvider)ctx.getBean("atom");
assertNotNull(provider);
provider.setFormattedOutput(true);
ByteArrayOutputStream bos=new ByteArrayOutputStream();
Books books=new Books();
List bs=new ArrayList();
bs.add(new Book("a"));
bs.add(new Book("b"));
books.setBooks(bs);
provider.writeTo(books,Books.class,Books.class,new Annotation[]{},MediaType.valueOf("application/atom+xml"),null,bos);
ByteArrayInputStream bis=new ByteArrayInputStream(bos.toByteArray());
Feed feed=new AtomFeedProvider().readFrom(Feed.class,null,null,null,null,bis);
assertEquals("Books",feed.getTitle());
List entries=feed.getEntries();
assertEquals(2,entries.size());
verifyEntry(getEntry(entries,"a"),"a");
verifyEntry(getEntry(entries,"b"),"b");
}
Class: org.apache.cxf.jaxrs.provider.dom4j.DOM4JProviderTest APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testReadJSONConvertToXML() throws Exception {
final String xml="{\"a\":{\"b\":2}}";
DOM4JProvider p=new DOM4JProvider();
p.setProviders(new ProvidersImpl(createMessage(false)));
org.dom4j.Document dom=p.readFrom(org.dom4j.Document.class,org.dom4j.Document.class,new Annotation[]{},MediaType.APPLICATION_JSON_TYPE,new MetadataMap(),new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
String str=dom.asXML();
assertTrue(str.contains("2 "));
}
Class: org.apache.cxf.jaxrs.provider.json.DataBindingJSONProviderTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testJAXBRead() throws Exception {
String data="{\"Book\":{\"id\":127,\"name\":\"CXF\",\"state\":\"\"}}";
Service s=new JAXRSServiceImpl(Collections.singletonList(c),true);
DataBinding binding=new JAXBDataBinding();
binding.initialize(s);
DataBindingJSONProvider p=new DataBindingJSONProvider();
p.setDataBinding(binding);
ByteArrayInputStream is=new ByteArrayInputStream(data.getBytes());
Book book=(Book)p.readFrom(Book.class,Book.class,new Annotation[0],MediaType.APPLICATION_JSON_TYPE,new MetadataMap(),is);
assertEquals("CXF",book.getName());
assertEquals(127L,book.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testSDORead() throws Exception {
String data="{\"p0.Structure\":{\"@xsi.type\":\"p0:Structure\",\"p0.text\":\"sdo\",\"p0.int\":3" + ",\"p0.dbl\":123.5,\"p0.texts\":\"text1\"}}";
Service s=new JAXRSServiceImpl(Collections.singletonList(c2),true);
DataBinding binding=new SDODataBinding();
binding.initialize(s);
DataBindingJSONProvider p=new DataBindingJSONProvider();
p.setDataBinding(binding);
p.setNamespaceMap(Collections.singletonMap("http://apache.org/structure/types","p0"));
ByteArrayInputStream is=new ByteArrayInputStream(data.getBytes());
Structure struct=p.readFrom(Structure.class,Structure.class,new Annotation[0],MediaType.APPLICATION_JSON_TYPE,new MetadataMap(),is);
assertEquals("sdo",struct.getText());
assertEquals(123.5,struct.getDbl(),0.01);
assertEquals(3,struct.getInt());
}
Class: org.apache.cxf.jaxrs.provider.json.JSONProviderTest InternalCallVerifier EqualityVerifier
@Test public void testReadFromUnwrappedQualifiedTagRoot() throws Exception {
JSONProvider p=new JSONProvider();
p.setSupportUnwrapped(true);
Map namespaceMap=new HashMap();
namespaceMap.put("http://tags","ns1");
p.setNamespaceMap(namespaceMap);
byte[] bytes="{\"group\":\"b\",\"name\":\"a\"}".getBytes();
Object tagsObject=p.readFrom(TagVO2.class,null,null,null,null,new ByteArrayInputStream(bytes));
TagVO2 tag=(TagVO2)tagsObject;
assertEquals("a",tag.getName());
assertEquals("b",tag.getGroup());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testReadListOfDerivedTypesWithNullField() throws Exception {
JSONProvider p=new JSONProvider();
Map namespaceMap=new HashMap();
namespaceMap.put("http://www.w3.org/2001/XMLSchema-instance","xsins");
p.setNamespaceMap(namespaceMap);
String data="{\"books2\":{\"books\":{\"@xsins.type\":\"superBook\",\"id\":123," + "\"name\":null,\"superId\":124}}}";
byte[] bytes=data.getBytes();
Object books2Object=p.readFrom(Books2.class,null,null,null,null,new ByteArrayInputStream(bytes));
Books2 books=(Books2)books2Object;
List extends Book> list=books.getBooks();
assertEquals(1,list.size());
SuperBook book=(SuperBook)list.get(0);
assertEquals(124L,book.getSuperId());
assertEquals(0,book.getName().length());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testReadEmbeddedArrayWithNamespaces() throws Exception {
String input="{\"ns1.store\":" + "{\"ns1.books\":{" + " \"ns1.thebook2\":["+ " { "+ " \"name\":\"CXF 1\""+ " }, "+ " { "+ " \"name\":\"CXF 2\""+ " } "+ " ] "+ " } "+ " } "+ "} ";
JSONProvider p=new JSONProvider();
Map namespaceMap=new HashMap();
namespaceMap.put("http://superbooks","ns1");
p.setNamespaceMap(namespaceMap);
Object storeObject=p.readFrom(QualifiedStore.class,null,null,null,null,new ByteArrayInputStream(input.getBytes()));
QualifiedStore store=(QualifiedStore)storeObject;
List books=store.getBooks();
assertEquals(2,books.size());
assertEquals("CXF 1",books.get(0).getName());
assertEquals("CXF 2",books.get(1).getName());
}
InternalCallVerifier EqualityVerifier
@Test public void testReadFromTag() throws Exception {
MessageBodyReader p=new JSONProvider();
byte[] bytes="{\"tagVO\":{\"group\":\"b\",\"name\":\"a\"}}".getBytes();
Object tagsObject=p.readFrom(TagVO.class,null,null,null,null,new ByteArrayInputStream(bytes));
TagVO tag=(TagVO)tagsObject;
assertEquals("a",tag.getName());
assertEquals("b",tag.getGroup());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testReadListOfDerivedTypes() throws Exception {
JSONProvider p=new JSONProvider();
Map namespaceMap=new HashMap();
namespaceMap.put("http://www.w3.org/2001/XMLSchema-instance","xsins");
p.setNamespaceMap(namespaceMap);
String data="{\"books2\":{\"books\":{\"@xsins.type\":\"superBook\",\"id\":123," + "\"name\":\"CXF Rocks\",\"superId\":124}}}";
byte[] bytes=data.getBytes();
Object books2Object=p.readFrom(Books2.class,null,null,null,null,new ByteArrayInputStream(bytes));
Books2 books=(Books2)books2Object;
List extends Book> list=books.getBooks();
assertEquals(1,list.size());
SuperBook book=(SuperBook)list.get(0);
assertEquals(124L,book.getSuperId());
assertEquals(123L,book.getId());
assertEquals("CXF Rocks",book.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testInNsElementsFromLocals() throws Exception {
String data="{tagholder:{thetag:{\"group\":\"B\",\"name\":\"A\"}}}";
JSONProvider provider=new JSONProvider();
Map map=new HashMap();
map.put("tagholder","{http://tags}tagholder");
map.put("thetag","{http://tags}thetag");
provider.setInTransformElements(map);
ByteArrayInputStream is=new ByteArrayInputStream(data.getBytes());
Object o=provider.readFrom(TagVO2Holder.class,TagVO2Holder.class,new Annotation[0],MediaType.TEXT_XML_TYPE,new MetadataMap(),is);
TagVO2Holder holder=(TagVO2Holder)o;
TagVO2 tag2=holder.getTagValue();
assertEquals("A",tag2.getName());
assertEquals("B",tag2.getGroup());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testReadListOfProperties() throws Exception {
String input="{\"theBook\":" + "{" + "\"Names\":[{\"Name\":\"1\"}, {\"Name\":\"2\"}]"+ " } "+ "} ";
JSONProvider provider=new JSONProvider();
provider.setPrimitiveArrayKeys(Collections.singletonList("Names"));
TheBook theBook=provider.readFrom(TheBook.class,null,null,null,null,new ByteArrayInputStream(input.getBytes()));
List names=theBook.getName();
assertNotNull(names);
assertEquals("1",names.get(0));
assertEquals("2",names.get(1));
}
InternalCallVerifier EqualityVerifier
@Test public void testReadFromTags() throws Exception {
MessageBodyReader p=new JSONProvider();
byte[] bytes="{\"Tags\":{\"list\":[{\"group\":\"b\",\"name\":\"a\"},{\"group\":\"d\",\"name\":\"c\"}]}}".getBytes();
Object tagsObject=p.readFrom(Tags.class,null,null,null,null,new ByteArrayInputStream(bytes));
Tags tags=(Tags)tagsObject;
List list=tags.getTags();
assertEquals(2,list.size());
assertEquals("a",list.get(0).getName());
assertEquals("b",list.get(0).getGroup());
assertEquals("c",list.get(1).getName());
assertEquals("d",list.get(1).getGroup());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testReadNullStringAsNull() throws Exception {
String input="{\"Book\":{\"id\":123,\"name\":\"null\"}}";
JSONProvider provider=new JSONProvider();
Book theBook=provider.readFrom(Book.class,null,null,null,null,new ByteArrayInputStream(input.getBytes()));
assertEquals(123L,theBook.getId());
assertEquals("",theBook.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testInDropElement() throws Exception {
String data="{\"Extra\":{\"ManyTags\":{\"tags\":{\"list\":[{\"group\":\"b\",\"name\":\"a\"}]}}}}";
JSONProvider provider=new JSONProvider();
provider.setInDropElements(Collections.singletonList("Extra"));
ByteArrayInputStream is=new ByteArrayInputStream(data.getBytes());
Object o=provider.readFrom(ManyTags.class,ManyTags.class,new Annotation[0],MediaType.APPLICATION_JSON_TYPE,new MetadataMap(),is);
ManyTags holder=(ManyTags)o;
assertNotNull(holder);
TagVO tag=holder.getTags().getTags().get(0);
assertEquals("a",tag.getName());
assertEquals("b",tag.getGroup());
}
Class: org.apache.cxf.jaxrs.provider.jsrjsonp.JsrJsonpProviderTest InternalCallVerifier ConditionMatcher
@Test public void testReadableTypes() throws Exception {
assertThat(provider.isReadable(JsonArray.class,null,null,null),equalTo(true));
assertThat(provider.isReadable(JsonStructure.class,null,null,null),equalTo(true));
assertThat(provider.isReadable(JsonObject.class,null,null,null),equalTo(true));
assertThat(provider.isReadable(JsonValue.class,null,null,null),equalTo(false));
}
APIUtilityVerifier InternalCallVerifier ConditionMatcher
@Test public void testReadJsonArray() throws Exception {
final StringWriter writer=new StringWriter();
Json.createGenerator(writer).writeStartArray().write("Tom").write("Tommyknocker").writeEnd().close();
final JsonStructure obj=provider.readFrom(JsonStructure.class,null,null,null,null,new ByteArrayInputStream(writer.toString().getBytes()));
assertThat(obj,instanceOf(JsonArray.class));
assertThat(((JsonArray)obj).getString(0),equalTo("Tom"));
assertThat(((JsonArray)obj).getString(1),equalTo("Tommyknocker"));
assertThat(((JsonArray)obj).size(),equalTo(2));
}
APIUtilityVerifier InternalCallVerifier ConditionMatcher
@Test public void testReadJsonObject() throws Exception {
final StringWriter writer=new StringWriter();
Json.createGenerator(writer).writeStartObject().write("firstName","Tom").write("lastName","Tommyknocker").writeEnd().close();
final String str=writer.toString();
writer.close();
final JsonStructure obj=provider.readFrom(JsonStructure.class,null,null,null,null,new ByteArrayInputStream(str.getBytes()));
assertThat(obj,instanceOf(JsonObject.class));
assertThat(((JsonObject)obj).getString("firstName"),equalTo("Tom"));
assertThat(((JsonObject)obj).getString("lastName"),equalTo("Tommyknocker"));
}
InternalCallVerifier ConditionMatcher
@Test public void testWritableTypes() throws Exception {
assertThat(provider.isWriteable(JsonArray.class,null,null,null),equalTo(true));
assertThat(provider.isWriteable(JsonStructure.class,null,null,null),equalTo(true));
assertThat(provider.isWriteable(JsonObject.class,null,null,null),equalTo(true));
assertThat(provider.isWriteable(JsonValue.class,null,null,null),equalTo(false));
}
Class: org.apache.cxf.jaxrs.security.JAASAuthenticationFilterTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testRFC2617() throws Exception {
JAASAuthenticationFilter filter=new JAASAuthenticationFilter();
filter.setRealmName("foo");
Message m=new MessageImpl();
Response r=filter.handleAuthenticationException(new SecurityException("Bad Auth"),m);
assertNotNull(r);
String result=r.getHeaderString(HttpHeaders.WWW_AUTHENTICATE);
assertNotNull(result);
assertEquals("Basic realm=\"foo\"",result);
}
Class: org.apache.cxf.jaxrs.servlet.AbstractSciTest InternalCallVerifier EqualityVerifier
@Test public void testResponseHasBeenReceivedWhenQueringBook(){
Response r=createWebClient("/bookstore/books").path("1").get();
assertEquals(Status.OK.getStatusCode(),r.getStatus());
Book book=r.readEntity(Book.class);
assertEquals("1",book.getId());
}
Class: org.apache.cxf.jaxrs.spring.JAXRSServerFactoryBeanTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testServers() throws Exception {
ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext(new String[]{"/org/apache/cxf/jaxrs/spring/servers.xml"});
JAXRSServerFactoryBean sfb=(JAXRSServerFactoryBean)ctx.getBean("simple");
assertEquals("Get a wrong address","http://localhost:9090/rs",sfb.getAddress());
assertNotNull("The resource classes should not be null",sfb.getResourceClasses());
assertEquals("Get a wrong resource class",BookStore.class,sfb.getResourceClasses().get(0));
QName serviceQName=new QName("http://books.com","BookService");
assertEquals(serviceQName,sfb.getServiceName());
assertEquals(serviceQName,sfb.getServiceFactory().getServiceName());
sfb=(JAXRSServerFactoryBean)ctx.getBean("inlineServiceBeans");
assertNotNull("The resource classes should not be null",sfb.getResourceClasses());
assertEquals("Get a wrong resource class",BookStore.class,sfb.getResourceClasses().get(0));
assertEquals("Get a wrong resource class",BookStoreSubresourcesOnly.class,sfb.getResourceClasses().get(1));
sfb=(JAXRSServerFactoryBean)ctx.getBean("inlineProvider");
assertNotNull("The provider should not be null",sfb.getProviders());
assertEquals("Get a wrong provider size",2,sfb.getProviders().size());
verifyJaxbProvider(sfb.getProviders());
sfb=(JAXRSServerFactoryBean)ctx.getBean("moduleServer");
assertNotNull("The resource classes should not be null",sfb.getResourceClasses());
assertEquals("Get a wrong ResourceClasses size",1,sfb.getResourceClasses().size());
assertEquals("Get a wrong resource class",BookStoreNoAnnotations.class,sfb.getResourceClasses().get(0));
ctx.close();
}
Class: org.apache.cxf.jaxrs.spring.SpringResourceFactoryTest InternalCallVerifier IdentityVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testFactory() throws Exception {
ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext(new String[]{"/org/apache/cxf/jaxrs/spring/servers2.xml"});
verifyFactory(ctx,"sfactory1",true);
verifyFactory(ctx,"sfactory2",false);
Object serverBean=ctx.getBean("server1");
assertNotNull(serverBean);
JAXRSServerFactoryBean factoryBean=(JAXRSServerFactoryBean)serverBean;
List list=factoryBean.getServiceFactory().getClassResourceInfo();
assertNotNull(list);
assertEquals(4,list.size());
assertSame(BookStoreConstructor.class,list.get(0).getServiceClass());
assertSame(BookStoreConstructor.class,list.get(0).getResourceClass());
assertSame(BookStore.class,list.get(1).getServiceClass());
assertSame(BookStore.class,list.get(1).getResourceClass());
}
Class: org.apache.cxf.jaxrs.swagger.Swagger2FeatureTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSetBasePathByAddress(){
Swagger2Feature f=new Swagger2Feature();
f.setBasePathByAddress("http://localhost:8080/foo");
assertEquals("/foo",f.getBasePath());
assertEquals("localhost:8080",f.getHost());
unsetBasePath(f);
f.setBasePathByAddress("http://localhost/foo");
assertEquals("/foo",f.getBasePath());
assertEquals("localhost",f.getHost());
unsetBasePath(f);
f.setBasePathByAddress("/foo");
assertEquals("/foo",f.getBasePath());
assertNull(f.getHost());
unsetBasePath(f);
}
Class: org.apache.cxf.jaxrs.swagger.SwaggerFeatureTest InternalCallVerifier EqualityVerifier
@Test public void testSetBasePathByAddress(){
SwaggerFeature f=new SwaggerFeature();
f.setBasePathByAddress("http://localhost:8080/foo");
assertEquals("http://localhost:8080/foo",f.getBasePath());
unsetBasePath(f);
f.setBasePathByAddress("/foo");
assertEquals("/foo",f.getBasePath());
unsetBasePath(f);
}
Class: org.apache.cxf.jaxrs.swagger.SwaggerUtilsTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testConvertSwagger20ToUserResource(){
UserResource ur=SwaggerUtils.getUserResource("/swagger20.json");
assertNotNull(ur);
assertEquals("/base",ur.getPath());
assertEquals(1,ur.getOperations().size());
UserOperation op=ur.getOperations().get(0);
assertEquals("postOp",op.getName());
assertEquals("/somepath",op.getPath());
assertEquals("POST",op.getVerb());
assertEquals("application/x-www-form-urlencoded",op.getConsumes());
assertEquals("application/json",op.getProduces());
assertEquals(3,op.getParameters().size());
Parameter param1=op.getParameters().get(0);
assertEquals("userName",param1.getName());
assertEquals(ParameterType.FORM,param1.getType());
assertEquals(String.class,param1.getJavaType());
Parameter param2=op.getParameters().get(1);
assertEquals("password",param2.getName());
assertEquals(ParameterType.FORM,param2.getType());
assertEquals(String.class,param2.getJavaType());
Parameter param3=op.getParameters().get(2);
assertEquals("type",param3.getName());
assertEquals(ParameterType.MATRIX,param3.getType());
assertEquals(String.class,param3.getJavaType());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testConvertSwagger12ToUserResource(){
UserResource ur=SwaggerUtils.getUserResource("/swagger12.json");
assertNotNull(ur);
assertEquals("/hello",ur.getPath());
assertEquals(1,ur.getOperations().size());
UserOperation op=ur.getOperations().get(0);
assertEquals("helloSubject",op.getName());
assertEquals("/{subject}",op.getPath());
assertEquals("GET",op.getVerb());
assertEquals(1,op.getParameters().size());
Parameter param=op.getParameters().get(0);
assertEquals("subject",param.getName());
assertEquals(ParameterType.PATH,param.getType());
assertEquals(String.class,param.getJavaType());
}
Class: org.apache.cxf.jaxrs.utils.FormUtilsTest InternalCallVerifier EqualityVerifier
@Test public void populateMapFromStringFromHTTP(){
mockObjects(null);
EasyMock.replay(mockMessage,mockRequest);
MultivaluedMap params=new MetadataMap();
FormUtils.populateMapFromString(params,mockMessage,null,StandardCharsets.UTF_8.name(),false,mockRequest);
assertEquals(2,params.size());
assertEquals(HTTP_PARAM_VALUE1,params.get(HTTP_PARAM1).iterator().next());
assertEquals(HTTP_PARAM_VALUE2,params.get(HTTP_PARAM2).iterator().next());
}
InternalCallVerifier EqualityVerifier
@Test public void populateMapFromStringFromBody(){
mockObjects(null);
EasyMock.replay(mockMessage,mockRequest);
MultivaluedMap params=new MetadataMap();
String postBody=FORM_PARAM1 + "=" + FORM_PARAM_VALUE1+ "&"+ FORM_PARAM2+ "="+ FORM_PARAM_VALUE2;
FormUtils.populateMapFromString(params,mockMessage,postBody,StandardCharsets.UTF_8.name(),false,mockRequest);
assertEquals(2,params.size());
assertEquals(FORM_PARAM_VALUE1,params.get(FORM_PARAM1).iterator().next());
assertEquals(FORM_PARAM_VALUE2,params.get(FORM_PARAM2).iterator().next());
}
Class: org.apache.cxf.jaxrs.utils.HttpUtilsTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testReplaceAnyIPAddress(){
Message m=new MessageImpl();
HttpServletRequest req=EasyMock.createMock(HttpServletRequest.class);
m.put(AbstractHTTPDestination.HTTP_REQUEST,req);
req.getScheme();
EasyMock.expectLastCall().andReturn("http");
req.getServerName();
EasyMock.expectLastCall().andReturn("localhost");
req.getServerPort();
EasyMock.expectLastCall().andReturn(8080);
EasyMock.replay(req);
URI u=HttpUtils.toAbsoluteUri(URI.create("http://0.0.0.0/bar/foo"),m);
assertEquals("http://localhost:8080/bar/foo",u.toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testUpdatePath(){
Message m=new MessageImpl();
m.setExchange(new ExchangeImpl());
m.put(Message.ENDPOINT_ADDRESS,"http://localhost/");
HttpUtils.updatePath(m,"/bar");
assertEquals("/bar",m.get(Message.REQUEST_URI));
HttpUtils.updatePath(m,"bar");
assertEquals("/bar",m.get(Message.REQUEST_URI));
HttpUtils.updatePath(m,"bar/");
assertEquals("/bar/",m.get(Message.REQUEST_URI));
m.put(Message.ENDPOINT_ADDRESS,"http://localhost");
HttpUtils.updatePath(m,"bar/");
assertEquals("/bar/",m.get(Message.REQUEST_URI));
}
Class: org.apache.cxf.jaxrs.utils.InjectionUtilsTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testExtractValuesFromBean(){
CustomerBean1 bean1=new CustomerBean1();
bean1.setA("aValue");
bean1.setB(1L);
List values=new ArrayList();
values.add("lv1");
values.add("lv2");
bean1.setC(values);
CustomerBean2 bean2=new CustomerBean2();
bean2.setA("aaValue");
bean2.setB(2L);
values=new ArrayList();
values.add("lv11");
values.add("lv22");
bean2.setC(values);
Set set=new HashSet();
set.add("set1");
set.add("set2");
bean2.setS(set);
bean1.setD(bean2);
MultivaluedMap map=InjectionUtils.extractValuesFromBean(bean1,"");
assertEquals("Size is wrong",7,map.size());
assertEquals(1,map.get("a").size());
assertEquals("aValue",map.getFirst("a"));
assertEquals(1,map.get("b").size());
assertEquals(1L,map.getFirst("b"));
assertEquals(2,map.get("c").size());
assertEquals("lv1",map.get("c").get(0));
assertEquals("lv2",map.get("c").get(1));
assertEquals(1,map.get("d.a").size());
assertEquals("aaValue",map.getFirst("d.a"));
assertEquals(1,map.get("d.b").size());
assertEquals(2L,map.getFirst("d.b"));
assertEquals(2,map.get("d.c").size());
assertEquals("lv11",map.get("d.c").get(0));
assertEquals("lv22",map.get("d.c").get(1));
assertEquals(2,map.get("d.s").size());
assertTrue(map.get("d.s").contains("set1"));
assertTrue(map.get("d.s").contains("set2"));
}
Class: org.apache.cxf.jaxrs.utils.JAXRSUtilsTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testFormParametersBeanWithMap() throws Exception {
Class>[] argType={Customer.CustomerBean.class};
Method m=Customer.class.getMethod("testFormBean",argType);
Message messageImpl=createMessage();
messageImpl.put(Message.REQUEST_URI,"/bar");
MultivaluedMap headers=new MetadataMap();
headers.putSingle("Content-Type",MediaType.APPLICATION_FORM_URLENCODED);
messageImpl.put(Message.PROTOCOL_HEADERS,headers);
String body="g.b=1&g.b=2";
messageImpl.setContent(InputStream.class,new ByteArrayInputStream(body.getBytes()));
List params=JAXRSUtils.processParameters(new OperationResourceInfo(m,new ClassResourceInfo(Customer.class)),null,messageImpl);
assertEquals("Bean should be created",1,params.size());
Customer.CustomerBean cb=(Customer.CustomerBean)params.get(0);
assertNotNull(cb);
assertNotNull(cb.getG());
List values=cb.getG().get("b");
assertEquals(2,values.size());
assertEquals("1",values.get(0));
assertEquals("2",values.get(1));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testQueryParameters() throws Exception {
Class>[] argType={String.class,Integer.TYPE,String.class,String.class};
Method m=Customer.class.getMethod("testQuery",argType);
Message messageImpl=createMessage();
messageImpl.put(Message.QUERY_STRING,"query=24&query2");
List params=JAXRSUtils.processParameters(new OperationResourceInfo(m,new ClassResourceInfo(Customer.class)),null,messageImpl);
assertEquals(4,params.size());
assertEquals("Query Parameter was not matched correctly","24",params.get(0));
assertEquals("Primitive Query Parameter was not matched correctly",24,params.get(1));
assertEquals("",params.get(2));
assertNull(params.get(3));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testArrayParamNoProvider() throws Exception {
Message messageImpl=createMessage();
Class>[] argType={String[].class};
Method m=Customer.class.getMethod("testCustomerParam2",argType);
messageImpl.put(Message.QUERY_STRING,"p1=Fred&p1=Barry");
List params=JAXRSUtils.processParameters(new OperationResourceInfo(m,new ClassResourceInfo(Customer.class)),null,messageImpl);
assertEquals(1,params.size());
String[] values=(String[])params.get(0);
assertEquals("Fred",values[0]);
assertEquals("Barry",values[1]);
}
BooleanVerifier InternalCallVerifier
@Test public void testIntersectMimeTypesCompositeSubtype10() throws Exception {
Message m=new MessageImpl();
m.put(JAXRSUtils.PARTIAL_HIERARCHICAL_MEDIA_SUBTYPE_CHECK,true);
assertFalse(JAXRSUtils.compareCompositeSubtypes("application/v1+xml","application/v2+xml",m));
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testContextResolverParam() throws Exception {
ClassResourceInfo cri=new ClassResourceInfo(Customer.class,true);
OperationResourceInfo ori=new OperationResourceInfo(Customer.class.getMethod("testContextResolvers",new Class[]{ContextResolver.class}),cri);
ori.setHttpMethod("GET");
Message m=createMessage();
ContextResolver cr=new JAXBContextProvider();
ProviderFactory.getInstance(m).registerUserProvider(cr);
m.put(Message.BASE_PATH,"/");
List params=JAXRSUtils.processParameters(ori,new MetadataMap(),m);
assertEquals("1 parameters expected",1,params.size());
assertSame(cr.getClass(),params.get(0).getClass());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testQueryParametersIntArray() throws Exception {
Class>[] argType={int[].class};
Method m=Customer.class.getMethod("testQueryIntArray",argType);
Message messageImpl=createMessage();
messageImpl.put(Message.QUERY_STRING,"query=1&query=2");
List params=JAXRSUtils.processParameters(new OperationResourceInfo(m,new ClassResourceInfo(Customer.class)),null,messageImpl);
assertEquals(1,params.size());
int[] intValues=(int[])params.get(0);
assertEquals(1,intValues[0]);
assertEquals(2,intValues[1]);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testXmlAdapterBean3() throws Exception {
Class>[] argType={Customer.CustomerBeanInterface.class};
Method m=Customer.class.getMethod("testXmlAdapter3",argType);
Message messageImpl=createMessage();
messageImpl.put(Message.QUERY_STRING,"a=aValue");
List params=JAXRSUtils.processParameters(new OperationResourceInfo(m,new ClassResourceInfo(Customer.class)),null,messageImpl);
assertEquals(1,params.size());
Customer.CustomerBean bean=(Customer.CustomerBean)params.get(0);
assertEquals("aValue",bean.getA());
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testHttpContextParametersFromInterface() throws Exception {
ClassResourceInfo cri=new ClassResourceInfo(Customer.class,true);
Method methodToInvoke=Customer.class.getMethod("setUriInfoContext",new Class[]{UriInfo.class});
OperationResourceInfo ori=new OperationResourceInfo(methodToInvoke,AnnotationUtils.getAnnotatedMethod(Customer.class,methodToInvoke),cri);
ori.setHttpMethod("GET");
Message m=new MessageImpl();
List params=JAXRSUtils.processParameters(ori,new MetadataMap(),m);
assertEquals("1 parameters expected",1,params.size());
assertSame(UriInfoImpl.class,params.get(0).getClass());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testFindTargetResourceClass() throws Exception {
JAXRSServiceFactoryBean sf=new JAXRSServiceFactoryBean();
sf.setResourceClasses(org.apache.cxf.jaxrs.resources.BookStoreNoSubResource.class);
sf.create();
List resources=((JAXRSServiceImpl)sf.getService()).getClassResourceInfos();
String contentTypes="*/*";
OperationResourceInfo ori=findTargetResourceClass(resources,createMessage2(),"/bookstore/1/books/123/","GET",new MetadataMap(),contentTypes,getTypes("application/json,application/xml;q=0.9"));
assertNotNull(ori);
assertEquals("getBookJSON",ori.getMethodToInvoke().getName());
ori=findTargetResourceClass(resources,createMessage2(),"/bookstore/1/books/123","GET",new MetadataMap(),contentTypes,getTypes("application/json"));
assertNotNull(ori);
assertEquals("getBookJSON",ori.getMethodToInvoke().getName());
ori=findTargetResourceClass(resources,createMessage2(),"/bookstore/1/books/123","GET",new MetadataMap(),contentTypes,getTypes("application/xml"));
assertNotNull(ori);
assertEquals("getBook",ori.getMethodToInvoke().getName());
ori=findTargetResourceClass(resources,createMessage2(),"/bookstore/1/books","GET",new MetadataMap(),contentTypes,getTypes("application/xml"));
assertNotNull(ori);
assertEquals("getBooks",ori.getMethodToInvoke().getName());
ori=findTargetResourceClass(resources,createMessage2(),"/bookstore/1/books","POST",new MetadataMap(),contentTypes,getTypes("application/xml"));
assertNotNull(ori);
assertEquals("addBook",ori.getMethodToInvoke().getName());
ori=findTargetResourceClass(resources,createMessage2(),"/bookstore/1/books","PUT",new MetadataMap(),contentTypes,getTypes("application/xml"));
assertEquals("updateBook",ori.getMethodToInvoke().getName());
ori=findTargetResourceClass(resources,createMessage2(),"/bookstore/1/books/123","DELETE",new MetadataMap(),contentTypes,getTypes("application/xml"));
assertNotNull(ori);
assertEquals("deleteBook",ori.getMethodToInvoke().getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testXmlAdapterBean2() throws Exception {
Class>[] argType={Customer.CustomerBean.class};
Method m=Customer.class.getMethod("testXmlAdapter2",argType);
Message messageImpl=createMessage();
messageImpl.put(Message.QUERY_STRING,"a=aValue");
List params=JAXRSUtils.processParameters(new OperationResourceInfo(m,new ClassResourceInfo(Customer.class)),null,messageImpl);
assertEquals(1,params.size());
Customer.CustomerBean bean=(Customer.CustomerBean)params.get(0);
assertEquals("aValue",bean.getA());
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testServletContextParameters() throws Exception {
ClassResourceInfo cri=new ClassResourceInfo(Customer.class,true);
OperationResourceInfo ori=new OperationResourceInfo(Customer.class.getMethod("testServletParams",new Class[]{HttpServletRequest.class,HttpServletResponse.class,ServletContext.class,ServletConfig.class}),cri);
ori.setHttpMethod("GET");
HttpServletRequest request=EasyMock.createMock(HttpServletRequest.class);
HttpServletResponse response=new HttpServletResponseFilter(EasyMock.createMock(HttpServletResponse.class),null);
ServletContext context=EasyMock.createMock(ServletContext.class);
ServletConfig config=EasyMock.createMock(ServletConfig.class);
EasyMock.replay(request);
EasyMock.replay(context);
EasyMock.replay(config);
Message m=new MessageImpl();
m.put(AbstractHTTPDestination.HTTP_REQUEST,request);
m.put(AbstractHTTPDestination.HTTP_RESPONSE,response);
m.put(AbstractHTTPDestination.HTTP_CONTEXT,context);
m.put(AbstractHTTPDestination.HTTP_CONFIG,config);
List params=JAXRSUtils.processParameters(ori,new MetadataMap(),m);
assertEquals("4 parameters expected",4,params.size());
assertSame(request.getClass(),((HttpServletRequestFilter)params.get(0)).getRequest().getClass());
assertSame(response.getClass(),params.get(1).getClass());
assertSame(context.getClass(),params.get(2).getClass());
assertSame(config.getClass(),params.get(3).getClass());
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testFromValueEnum() throws Exception {
Class>[] argType={Timezone.class};
Method m=Customer.class.getMethod("testFromValueParam",argType);
Message messageImpl=createMessage();
messageImpl.put(Message.QUERY_STRING,"p1=Europe%2FLondon");
List params=JAXRSUtils.processParameters(new OperationResourceInfo(m,new ClassResourceInfo(Customer.class)),null,messageImpl);
assertEquals(1,params.size());
assertSame("Timezone Parameter was not processed correctly",Timezone.EUROPE_LONDON,params.get(0));
}
InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testServletResourceFields() throws Exception {
ClassResourceInfo cri=new ClassResourceInfo(Customer.class,true);
cri.setResourceProvider(new PerRequestResourceProvider(Customer.class));
OperationResourceInfo ori=new OperationResourceInfo(Customer.class.getMethod("postConstruct",new Class[]{}),cri);
Customer c=new Customer();
HttpServletRequest request=EasyMock.createMock(HttpServletRequest.class);
HttpServletResponse response=EasyMock.createMock(HttpServletResponse.class);
ServletContext context=EasyMock.createMock(ServletContext.class);
EasyMock.replay(request);
EasyMock.replay(response);
EasyMock.replay(context);
Message m=createMessage();
m.put(AbstractHTTPDestination.HTTP_REQUEST,request);
m.put(AbstractHTTPDestination.HTTP_RESPONSE,response);
m.put(AbstractHTTPDestination.HTTP_CONTEXT,context);
InjectionUtils.injectContextFields(c,ori.getClassResourceInfo(),m);
assertSame(request.getClass(),((HttpServletRequestFilter)c.getServletRequestResource()).getRequest().getClass());
HttpServletResponseFilter filter=(HttpServletResponseFilter)c.getServletResponseResource();
assertSame(response.getClass(),filter.getResponse().getClass());
assertSame(context.getClass(),c.getServletContextResource().getClass());
assertNotNull(c.getServletRequest());
assertNotNull(c.getServletResponse());
assertNotNull(c.getServletContext());
assertNotNull(c.getServletRequestResource());
assertNotNull(c.getServletResponseResource());
assertNotNull(c.getServletContextResource());
assertSame(request.getClass(),((HttpServletRequestFilter)c.getServletRequestResource()).getRequest().getClass());
filter=(HttpServletResponseFilter)c.getServletResponse();
assertSame(response.getClass(),filter.getResponse().getClass());
assertSame(context.getClass(),c.getServletContext().getClass());
}
BooleanVerifier InternalCallVerifier
@Test public void testIntersectMimeTypesCompositeSubtype11() throws Exception {
Message m=new MessageImpl();
m.put(JAXRSUtils.PARTIAL_HIERARCHICAL_MEDIA_SUBTYPE_CHECK,true);
assertFalse(JAXRSUtils.compareCompositeSubtypes("application/v1+xml","application/json",m));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testXmlAdapterBean() throws Exception {
Class>[] argType={Customer.CustomerBean.class};
Method m=Customer.class.getMethod("testXmlAdapter",argType);
Message messageImpl=createMessage();
messageImpl.put(Message.QUERY_STRING,"a=aValue");
List params=JAXRSUtils.processParameters(new OperationResourceInfo(m,new ClassResourceInfo(Customer.class)),null,messageImpl);
assertEquals(1,params.size());
Customer.CustomerBean bean=(Customer.CustomerBean)params.get(0);
assertEquals("aValue",bean.getA());
}
APIUtilityVerifier UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testCustomerParameter() throws Exception {
Message messageImpl=createMessage();
ServerProviderFactory.getInstance(messageImpl).registerUserProvider(new CustomerParameterHandler());
Class>[] argType={Customer.class,Customer[].class,Customer2.class};
Method m=Customer.class.getMethod("testCustomerParam",argType);
messageImpl.put(Message.QUERY_STRING,"p1=Fred&p2=Barry&p3=Jack&p4=John");
List params=JAXRSUtils.processParameters(new OperationResourceInfo(m,new ClassResourceInfo(Customer.class)),null,messageImpl);
assertEquals(3,params.size());
Customer c=(Customer)params.get(0);
assertEquals("Fred",c.getName());
Customer c2=((Customer[])params.get(1))[0];
assertEquals("Barry",c2.getName());
Customer2 c3=(Customer2)params.get(2);
assertEquals("Jack",c3.getName());
try {
messageImpl.put(Message.QUERY_STRING,"p3=noName");
JAXRSUtils.processParameters(new OperationResourceInfo(m,null),null,messageImpl);
fail("Customer2 constructor does not accept names starting with lower-case chars");
}
catch ( Exception ex) {
}
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testInjectCustomContext() throws Exception {
final CustomerContext contextImpl=new CustomerContext(){
public String get(){
return "customerContext";
}
}
;
JAXRSServerFactoryBean sf=new JAXRSServerFactoryBean();
Customer customer=new Customer();
sf.setServiceBeanObjects(customer);
sf.setProvider(new ContextProvider(){
public CustomerContext createContext( Message message){
return contextImpl;
}
}
);
sf.setStart(false);
Server s=sf.create();
assertTrue(customer.getCustomerContext() instanceof ThreadLocalProxy>);
invokeCustomerMethod(sf.getServiceFactory().getClassResourceInfo().get(0),customer,s);
CustomerContext context=customer.getCustomerContext();
assertEquals("customerContext",context.get());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testConversion() throws Exception {
ClassResourceInfo cri=new ClassResourceInfo(Customer.class,true);
OperationResourceInfo ori=new OperationResourceInfo(Customer.class.getMethod("testConversion",new Class[]{PathSegmentImpl.class,SimpleFactory.class}),cri);
ori.setHttpMethod("GET");
ori.setURITemplate(new URITemplate("{id1}/{id2}"));
MultivaluedMap values=new MetadataMap();
values.putSingle("id1","1");
values.putSingle("id2","2");
Message m=createMessage();
List params=JAXRSUtils.processParameters(ori,values,m);
PathSegment ps=(PathSegment)params.get(0);
assertEquals("1",ps.getPath());
SimpleFactory sf=(SimpleFactory)params.get(1);
assertEquals(2,sf.getId());
}
InternalCallVerifier IdentityVerifier
@SuppressWarnings("unchecked") @Test public void testSingletonContextFields() throws Exception {
ClassResourceInfo cri=new ClassResourceInfo(Customer.class,true);
Customer c=new Customer();
cri.setResourceProvider(new SingletonResourceProvider(c));
Message m=createMessage();
m.put(Message.PROTOCOL_HEADERS,new HashMap>());
ServletContext servletContextMock=EasyMock.createNiceMock(ServletContext.class);
m.put(AbstractHTTPDestination.HTTP_CONTEXT,servletContextMock);
HttpServletRequest httpRequest=EasyMock.createNiceMock(HttpServletRequest.class);
m.put(AbstractHTTPDestination.HTTP_REQUEST,httpRequest);
HttpServletResponse httpResponse=EasyMock.createMock(HttpServletResponse.class);
m.put(AbstractHTTPDestination.HTTP_RESPONSE,httpResponse);
InjectionUtils.injectContextProxies(cri,cri.getResourceProvider().getInstance(null));
InjectionUtils.injectContextFields(c,cri,m);
InjectionUtils.injectContextMethods(c,cri,m);
assertSame(ThreadLocalUriInfo.class,c.getUriInfo2().getClass());
assertSame(UriInfoImpl.class,((ThreadLocalProxy)c.getUriInfo2()).get().getClass());
assertSame(HttpHeadersImpl.class,((ThreadLocalProxy)c.getHeaders()).get().getClass());
assertSame(RequestImpl.class,((ThreadLocalProxy)c.getRequest()).get().getClass());
assertSame(ResourceInfoImpl.class,((ThreadLocalProxy)c.getResourceInfo()).get().getClass());
assertSame(SecurityContextImpl.class,((ThreadLocalProxy)c.getSecurityContext()).get().getClass());
assertSame(ProvidersImpl.class,((ThreadLocalProxy)c.getBodyWorkers()).get().getClass());
assertSame(servletContextMock,((ThreadLocalProxy)c.getThreadLocalServletContext()).get());
assertSame(servletContextMock,((ThreadLocalProxy)c.getServletContext()).get());
assertSame(servletContextMock,((ThreadLocalProxy)c.getSuperServletContext()).get());
HttpServletRequest currentReq=((ThreadLocalProxy)c.getServletRequest()).get();
assertSame(httpRequest,((HttpServletRequestFilter)currentReq).getRequest());
HttpServletResponseFilter filter=(HttpServletResponseFilter)((ThreadLocalProxy)c.getServletResponse()).get();
assertSame(httpResponse,filter.getResponse());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@SuppressWarnings("unchecked") @Test public void testQueryParamAsListWithDefaultValue() throws Exception {
Class>[] argType={List.class,List.class,List.class,Integer[].class,List.class,List.class};
Method m=Customer.class.getMethod("testQueryAsList",argType);
Message messageImpl=createMessage();
messageImpl.put(Message.QUERY_STRING,"query2=query2Value&query2=query2Value2&query3=1&query3=2&query4");
List params=JAXRSUtils.processParameters(new OperationResourceInfo(m,new ClassResourceInfo(Customer.class)),null,messageImpl);
assertEquals(6,params.size());
List queryList=(List)params.get(0);
assertNotNull(queryList);
assertEquals(1,queryList.size());
assertEquals("default",queryList.get(0));
List queryList2=(List)params.get(1);
assertNotNull(queryList2);
assertEquals(2,queryList2.size());
assertEquals("query2Value",queryList2.get(0));
assertEquals("query2Value2",queryList2.get(1));
List queryList3=(List)params.get(2);
assertNotNull(queryList3);
assertEquals(2,queryList3.size());
assertEquals(Integer.valueOf(1),queryList3.get(0));
assertEquals(Integer.valueOf(2),queryList3.get(1));
Integer[] queryList3Array=(Integer[])params.get(3);
assertNotNull(queryList3Array);
assertEquals(2,queryList3Array.length);
assertEquals(Integer.valueOf(1),queryList3Array[0]);
assertEquals(Integer.valueOf(2),queryList3Array[1]);
List queryList4=(List)params.get(4);
assertNotNull(queryList4);
assertEquals(1,queryList4.size());
assertEquals("",queryList4.get(0));
List queryList5=(List)params.get(5);
assertNotNull(queryList5);
assertEquals(0,queryList5.size());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@SuppressWarnings("unchecked") @Test public void testMatrixParameters() throws Exception {
Class>[] argType={String.class,String.class,String.class,String.class,List.class,String.class};
Method m=Customer.class.getMethod("testMatrixParam",argType);
Message messageImpl=createMessage();
messageImpl.put(Message.REQUEST_URI,"/foo;p4=0;p3=3/bar;p1=1;p2/baz;p4=4;p4=5;p5");
List params=JAXRSUtils.processParameters(new OperationResourceInfo(m,new ClassResourceInfo(Customer.class)),null,messageImpl);
assertEquals("5 Matrix params should've been identified",6,params.size());
assertEquals("First Matrix Parameter not matched correctly","1",params.get(0));
assertEquals("Second Matrix Parameter was not matched correctly","",params.get(1));
assertEquals("Third Matrix Parameter was not matched correctly","3",params.get(2));
assertEquals("Fourth Matrix Parameter was not matched correctly","0",params.get(3));
List list=(List)params.get(4);
assertEquals(3,list.size());
assertEquals("0",list.get(0));
assertEquals("4",list.get(1));
assertEquals("5",list.get(2));
assertEquals("Sixth Matrix Parameter was not matched correctly","",params.get(5));
}
InternalCallVerifier IdentityVerifier
@SuppressWarnings("unchecked") @Test public void testSingletonHttpResourceFields() throws Exception {
ClassResourceInfo cri=new ClassResourceInfo(Customer.class,true);
Customer c=new Customer();
cri.setResourceProvider(new SingletonResourceProvider(c));
Message m=createMessage();
ServletContext servletContextMock=EasyMock.createNiceMock(ServletContext.class);
m.put(AbstractHTTPDestination.HTTP_CONTEXT,servletContextMock);
HttpServletRequest httpRequest=EasyMock.createNiceMock(HttpServletRequest.class);
m.put(AbstractHTTPDestination.HTTP_REQUEST,httpRequest);
HttpServletResponse httpResponse=EasyMock.createMock(HttpServletResponse.class);
m.put(AbstractHTTPDestination.HTTP_RESPONSE,httpResponse);
InjectionUtils.injectContextProxies(cri,cri.getResourceProvider().getInstance(null));
InjectionUtils.injectContextFields(c,cri,m);
assertSame(servletContextMock,((ThreadLocalProxy)c.getServletContextResource()).get());
HttpServletRequest currentReq=((ThreadLocalProxy)c.getServletRequestResource()).get();
assertSame(httpRequest,((HttpServletRequestFilter)currentReq).getRequest());
HttpServletResponseFilter filter=(HttpServletResponseFilter)((ThreadLocalProxy)c.getServletResponseResource()).get();
assertSame(httpResponse,filter.getResponse());
}
BooleanVerifier InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testInjectApplicationInPerRequestResource() throws Exception {
CustomerApplication app=new CustomerApplication();
JAXRSServerFactoryBean sf=new JAXRSServerFactoryBean();
sf.setServiceClass(Customer.class);
sf.setApplication(app);
sf.setStart(false);
Server server=sf.create();
@SuppressWarnings("unchecked") ThreadLocalProxy proxy=(ThreadLocalProxy)app.getUriInfo();
assertNotNull(proxy);
ClassResourceInfo cri=sf.getServiceFactory().getClassResourceInfo().get(0);
Customer customer=(Customer)cri.getResourceProvider().getInstance(createMessage());
assertNull(customer.getApplication1());
assertNull(customer.getApplication2());
invokeCustomerMethod(cri,customer,server);
assertSame(app,customer.getApplication1());
assertSame(app,customer.getApplication2());
assertTrue(proxy.get() instanceof UriInfo);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testQueryParametersIntegerArray() throws Exception {
Class>[] argType={Integer[].class};
Method m=Customer.class.getMethod("testQueryIntegerArray",argType);
Message messageImpl=createMessage();
messageImpl.put(Message.QUERY_STRING,"query=1&query=2");
List params=JAXRSUtils.processParameters(new OperationResourceInfo(m,new ClassResourceInfo(Customer.class)),null,messageImpl);
assertEquals(1,params.size());
Integer[] intValues=(Integer[])params.get(0);
assertEquals(1,(int)intValues[0]);
assertEquals(2,(int)intValues[1]);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testMultipleQueryParameters() throws Exception {
Class>[] argType={String.class,String.class,Long.class,Boolean.TYPE,char.class,String.class};
Method m=Customer.class.getMethod("testMultipleQuery",argType);
Message messageImpl=createMessage();
messageImpl.put(Message.QUERY_STRING,"query=first&query2=second&query3=3&query4=true&query6");
List params=JAXRSUtils.processParameters(new OperationResourceInfo(m,new ClassResourceInfo(Customer.class)),null,messageImpl);
assertEquals("First Query Parameter of multiple was not matched correctly","first",params.get(0));
assertEquals("Second Query Parameter of multiple was not matched correctly","second",params.get(1));
assertEquals("Third Query Parameter of multiple was not matched correctly",new Long(3),params.get(2));
assertEquals("Fourth Query Parameter of multiple was not matched correctly",Boolean.TRUE,params.get(3));
assertEquals("Fifth Query Parameter of multiple was not matched correctly",'\u0000',params.get(4));
assertEquals("Six Query Parameter of multiple was not matched correctly","",params.get(5));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testCookieParameters() throws Exception {
Class>[] argType={String.class,Set.class,String.class,Set.class};
Method m=Customer.class.getMethod("testCookieParam",argType);
Message messageImpl=createMessage();
MultivaluedMap headers=new MetadataMap();
headers.add("Cookie","c1=c1Value");
messageImpl.put(Message.PROTOCOL_HEADERS,headers);
List params=JAXRSUtils.processParameters(new OperationResourceInfo(m,new ClassResourceInfo(Customer.class)),null,messageImpl);
assertEquals(params.size(),4);
assertEquals("c1Value",params.get(0));
Set set1=CastUtils.cast((Set>)params.get(1));
assertEquals(1,set1.size());
assertTrue(set1.contains(Cookie.valueOf("c1=c1Value")));
assertEquals("c2Value",params.get(2));
Set set2=CastUtils.cast((Set>)params.get(3));
assertTrue(set2.contains("c2Value"));
assertEquals(1,set2.size());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testSelectBetweenMultipleResourceClasses() throws Exception {
JAXRSServiceFactoryBean sf=new JAXRSServiceFactoryBean();
sf.setResourceClasses(org.apache.cxf.jaxrs.resources.BookStoreNoSubResource.class,org.apache.cxf.jaxrs.resources.BookStore.class);
sf.create();
List resources=((JAXRSServiceImpl)sf.getService()).getClassResourceInfos();
ClassResourceInfo bStore=firstResource(JAXRSUtils.selectResourceClass(resources,"/bookstore",null));
assertEquals(bStore.getResourceClass(),org.apache.cxf.jaxrs.resources.BookStore.class);
bStore=firstResource(JAXRSUtils.selectResourceClass(resources,"/bookstore/",null));
assertEquals(bStore.getResourceClass(),org.apache.cxf.jaxrs.resources.BookStore.class);
bStore=firstResource(JAXRSUtils.selectResourceClass(resources,"/bookstore/bar",null));
assertEquals(bStore.getResourceClass(),org.apache.cxf.jaxrs.resources.BookStoreNoSubResource.class);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testLocaleParameter() throws Exception {
Message messageImpl=createMessage();
ProviderFactory.getInstance(messageImpl).registerUserProvider(new LocaleParameterHandler());
Class>[] argType={Locale.class};
Method m=Customer.class.getMethod("testLocaleParam",argType);
messageImpl.put(Message.QUERY_STRING,"p1=en_us");
List params=JAXRSUtils.processParameters(new OperationResourceInfo(m,new ClassResourceInfo(Customer.class)),null,messageImpl);
assertEquals(1,params.size());
Locale l=(Locale)params.get(0);
assertEquals("en",l.getLanguage());
assertEquals("US",l.getCountry());
}
InternalCallVerifier EqualityVerifier
@Test public void testParamAnnotationOnMethod() throws Exception {
ClassResourceInfo cri=new ClassResourceInfo(Customer.class,true);
Customer c=new Customer();
OperationResourceInfo ori=new OperationResourceInfo(Customer.class.getMethods()[0],cri);
Message m=createMessage();
MultivaluedMap headers=new MetadataMap();
headers.add("AHeader2","theAHeader2");
m.put(Message.PROTOCOL_HEADERS,headers);
m.put(Message.QUERY_STRING,"a_value=aValue&query2=b");
JAXRSUtils.injectParameters(ori,c,m);
assertEquals("aValue",c.getQueryParam());
assertEquals("theAHeader2",c.getAHeader2());
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier
@Test public void testSelectResourceMethod() throws Exception {
ClassResourceInfo cri=new ClassResourceInfo(Customer.class);
OperationResourceInfo ori1=new OperationResourceInfo(Customer.class.getMethod("getItAsXML",new Class[]{}),cri);
ori1.setHttpMethod("GET");
ori1.setURITemplate(new URITemplate("/"));
OperationResourceInfo ori2=new OperationResourceInfo(Customer.class.getMethod("getItPlain",new Class[]{}),cri);
ori2.setHttpMethod("GET");
ori2.setURITemplate(new URITemplate("/"));
MethodDispatcher md=new MethodDispatcher();
md.bind(ori1,Customer.class.getMethod("getItAsXML",new Class[]{}));
md.bind(ori2,Customer.class.getMethod("getItPlain",new Class[]{}));
cri.setMethodDispatcher(md);
OperationResourceInfo ori=JAXRSUtils.findTargetMethod(getMap(cri),createMessage2(),"GET",new MetadataMap(),"*/*",getTypes("text/plain"));
assertSame(ori,ori2);
ori=JAXRSUtils.findTargetMethod(getMap(cri),createMessage2(),"GET",new MetadataMap(),"*/*",getTypes("text/xml"));
assertSame(ori,ori1);
ori=JAXRSUtils.findTargetMethod(getMap(cri),createMessage2(),"GET",new MetadataMap(),"*/*",sortMediaTypes(getTypes("*/*;q=0.1,text/plain,text/xml;q=0.8")));
assertSame(ori,ori2);
ori=JAXRSUtils.findTargetMethod(getMap(cri),createMessage2(),"GET",new MetadataMap(),"*/*",sortMediaTypes(getTypes("*;q=0.1,text/plain,text/xml;q=0.9,x/y")));
assertSame(ori,ori2);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testSelectBetweenMultipleResourceClasses2() throws Exception {
JAXRSServiceFactoryBean sf=new JAXRSServiceFactoryBean();
sf.setResourceClasses(org.apache.cxf.jaxrs.resources.TestResourceTemplate1.class,org.apache.cxf.jaxrs.resources.TestResourceTemplate2.class);
sf.create();
List resources=((JAXRSServiceImpl)sf.getService()).getClassResourceInfos();
ClassResourceInfo bStore=firstResource(JAXRSUtils.selectResourceClass(resources,"/1",null));
assertEquals(bStore.getResourceClass(),org.apache.cxf.jaxrs.resources.TestResourceTemplate1.class);
bStore=firstResource(JAXRSUtils.selectResourceClass(resources,"/1/",null));
assertEquals(bStore.getResourceClass(),org.apache.cxf.jaxrs.resources.TestResourceTemplate1.class);
bStore=firstResource(JAXRSUtils.selectResourceClass(resources,"/1/foo",null));
assertEquals(bStore.getResourceClass(),org.apache.cxf.jaxrs.resources.TestResourceTemplate2.class);
bStore=firstResource(JAXRSUtils.selectResourceClass(resources,"/1/foo/bar",null));
assertEquals(bStore.getResourceClass(),org.apache.cxf.jaxrs.resources.TestResourceTemplate2.class);
}
BooleanVerifier InternalCallVerifier
@Test public void testIntersectMimeTypesCompositeSubtype6() throws Exception {
Message m=new MessageImpl();
m.put(JAXRSUtils.PARTIAL_HIERARCHICAL_MEDIA_SUBTYPE_CHECK,true);
assertTrue(JAXRSUtils.compareCompositeSubtypes("application/bar+xml","application/xml",m));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testQueryParameter() throws Exception {
Message messageImpl=createMessage();
ProviderFactory.getInstance(messageImpl).registerUserProvider(new GenericObjectParameterHandler());
Class>[] argType={Query.class};
Method m=Customer.class.getMethod("testGenericObjectParam",argType);
messageImpl.put(Message.QUERY_STRING,"p1=thequery");
List params=JAXRSUtils.processParameters(new OperationResourceInfo(m,new ClassResourceInfo(Customer.class)),null,messageImpl);
assertEquals(1,params.size());
@SuppressWarnings("unchecked") Query query=(Query)params.get(0);
assertEquals("thequery",query.getEntity());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testMultipleCookieParameters() throws Exception {
Class>[] argType={String.class,String.class,Cookie.class};
Method m=Customer.class.getMethod("testMultipleCookieParam",argType);
Message messageImpl=createMessage();
MultivaluedMap headers=new MetadataMap();
headers.add("Cookie","c1=c1Value; c2=c2Value");
headers.add("Cookie","c3=c3Value");
messageImpl.put(Message.PROTOCOL_HEADERS,headers);
List params=JAXRSUtils.processParameters(new OperationResourceInfo(m,new ClassResourceInfo(Customer.class)),null,messageImpl);
assertEquals(params.size(),3);
assertEquals("c1Value",params.get(0));
assertEquals("c2Value",params.get(1));
assertEquals("c3Value",((Cookie)params.get(2)).getValue());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testSelectBetweenMultipleResourceClasses3() throws Exception {
JAXRSServiceFactoryBean sf=new JAXRSServiceFactoryBean();
sf.setResourceClasses(org.apache.cxf.jaxrs.resources.TestResourceTemplate4.class,org.apache.cxf.jaxrs.resources.TestResourceTemplate3.class);
sf.create();
List resources=((JAXRSServiceImpl)sf.getService()).getClassResourceInfos();
ClassResourceInfo bStore=firstResource(JAXRSUtils.selectResourceClass(resources,"/",null));
assertEquals(bStore.getResourceClass(),org.apache.cxf.jaxrs.resources.TestResourceTemplate3.class);
bStore=firstResource(JAXRSUtils.selectResourceClass(resources,"/test",null));
assertEquals(bStore.getResourceClass(),org.apache.cxf.jaxrs.resources.TestResourceTemplate4.class);
}
InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@SuppressWarnings("unchecked") @Test public void testContextAnnotationOnMethod() throws Exception {
ClassResourceInfo cri=new ClassResourceInfo(Customer.class,true);
Customer c=new Customer();
cri.setResourceProvider(new SingletonResourceProvider(c));
InjectionUtils.injectContextProxies(cri,cri.getResourceProvider().getInstance(null));
OperationResourceInfo ori=new OperationResourceInfo(Customer.class.getMethods()[0],cri);
Message message=createMessage();
InjectionUtils.injectContextMethods(c,ori.getClassResourceInfo(),message);
assertNotNull(c.getUriInfo());
assertSame(ThreadLocalUriInfo.class,c.getUriInfo().getClass());
assertSame(UriInfoImpl.class,((ThreadLocalProxy)c.getUriInfo()).get().getClass());
assertSame(ThreadLocalServletConfig.class,c.getSuperServletConfig().getClass());
assertSame(ThreadLocalHttpServletRequest.class,c.getHttpServletRequest().getClass());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testFindTargetResourceClassWithSubResource() throws Exception {
JAXRSServiceFactoryBean sf=new JAXRSServiceFactoryBean();
sf.setResourceClasses(org.apache.cxf.jaxrs.resources.BookStore.class);
sf.create();
List resources=((JAXRSServiceImpl)sf.getService()).getClassResourceInfos();
String contentTypes="*/*";
OperationResourceInfo ori=findTargetResourceClass(resources,createMessage2(),"/bookstore/books/sub/123","GET",new MetadataMap(),contentTypes,getTypes("*/*"));
assertNotNull(ori);
assertEquals("getBook",ori.getMethodToInvoke().getName());
ori=findTargetResourceClass(resources,createMessage2(),"/bookstore/books/123/true/chapter/1","GET",new MetadataMap(),contentTypes,getTypes("*/*"));
assertNotNull(ori);
assertEquals("getNewBook",ori.getMethodToInvoke().getName());
ori=findTargetResourceClass(resources,createMessage2(),"/bookstore/books","POST",new MetadataMap(),contentTypes,getTypes("*/*"));
assertNotNull(ori);
assertEquals("addBook",ori.getMethodToInvoke().getName());
ori=findTargetResourceClass(resources,createMessage2(),"/bookstore/books","PUT",new MetadataMap(),contentTypes,getTypes("*/*"));
assertNotNull(ori);
assertEquals("updateBook",ori.getMethodToInvoke().getName());
ori=findTargetResourceClass(resources,createMessage2(),"/bookstore/books/123","DELETE",new MetadataMap(),contentTypes,getTypes("*/*"));
assertNotNull(ori);
assertEquals("deleteBook",ori.getMethodToInvoke().getName());
}
BooleanVerifier InternalCallVerifier
@Test public void testIntersectMimeTypesCompositeSubtype8() throws Exception {
Message m=new MessageImpl();
m.put(JAXRSUtils.PARTIAL_HIERARCHICAL_MEDIA_SUBTYPE_CHECK,true);
assertTrue(JAXRSUtils.compareCompositeSubtypes("application/xml+bar","application/xml",m));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testMatrixAndPathSegmentParameters() throws Exception {
Class>[] argType={PathSegment.class,String.class};
Method m=Customer.class.getMethod("testPathSegment",argType);
Message messageImpl=createMessage();
messageImpl.put(Message.REQUEST_URI,"/bar%20foo;p4=0%201");
MultivaluedMap values=new MetadataMap();
values.add("ps","bar%20foo;p4=0%201");
List params=JAXRSUtils.processParameters(new OperationResourceInfo(m,new ClassResourceInfo(Customer.class)),values,messageImpl);
assertEquals("2 params should've been identified",2,params.size());
PathSegment ps=(PathSegment)params.get(0);
assertEquals("bar foo",ps.getPath());
assertEquals(1,ps.getMatrixParameters().size());
assertEquals("0 1",ps.getMatrixParameters().getFirst("p4"));
assertEquals("bar foo",params.get(1));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testFormParametersBeanWithBoolean() throws Exception {
Class>[] argType={Customer.CustomerBean.class};
Method m=Customer.class.getMethod("testFormBean",argType);
Message messageImpl=createMessage();
messageImpl.put(Message.REQUEST_URI,"/bar");
MultivaluedMap headers=new MetadataMap();
headers.putSingle("Content-Type",MediaType.APPLICATION_FORM_URLENCODED);
messageImpl.put(Message.PROTOCOL_HEADERS,headers);
String body="a=aValue&b=123&cb=true";
messageImpl.setContent(InputStream.class,new ByteArrayInputStream(body.getBytes()));
List params=JAXRSUtils.processParameters(new OperationResourceInfo(m,new ClassResourceInfo(Customer.class)),null,messageImpl);
assertEquals("Bean should be created",1,params.size());
Customer.CustomerBean cb=(Customer.CustomerBean)params.get(0);
assertNotNull(cb);
assertEquals("aValue",cb.getA());
assertEquals(new Long(123),cb.getB());
assertTrue(cb.isCb());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@SuppressWarnings("unchecked") @Test public void testFormParametersAndMap() throws Exception {
Class>[] argType={MultivaluedMap.class,String.class,List.class};
Method m=Customer.class.getMethod("testMultivaluedMapAndFormParam",argType);
final Message messageImpl=createMessage();
String body="p1=1&p2=2&p2=3";
messageImpl.put(Message.REQUEST_URI,"/foo");
messageImpl.put("Content-Type",MediaType.APPLICATION_FORM_URLENCODED);
messageImpl.setContent(InputStream.class,new ByteArrayInputStream(body.getBytes()));
ProviderFactory.getInstance(messageImpl).registerUserProvider(new FormEncodingProvider(){
@Override protected void persistParamsOnMessage( MultivaluedMap params){
messageImpl.put(FormUtils.FORM_PARAM_MAP,params);
}
}
);
List params=JAXRSUtils.processParameters(new OperationResourceInfo(m,new ClassResourceInfo(Customer.class)),new MetadataMap(),messageImpl);
assertEquals("3 params should've been identified",3,params.size());
MultivaluedMap map=(MultivaluedMap)params.get(0);
assertEquals(2,map.size());
assertEquals(1,map.get("p1").size());
assertEquals("First map parameter not matched correctly","1",map.getFirst("p1"));
assertEquals(2,map.get("p2").size());
assertEquals("2",map.get("p2").get(0));
assertEquals("3",map.get("p2").get(1));
assertEquals("First Form Parameter not matched correctly","1",params.get(1));
List list=(List)params.get(2);
assertEquals(2,list.size());
assertEquals("2",list.get(0));
assertEquals("3",list.get(1));
}
BooleanVerifier InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testInjectApplicationInSingleton() throws Exception {
CustomerApplication app=new CustomerApplication();
JAXRSServerFactoryBean sf=new JAXRSServerFactoryBean();
Customer customer=new Customer();
sf.setServiceBeanObjects(customer);
sf.setApplication(app);
sf.setStart(false);
Server server=sf.create();
assertSame(app,customer.getApplication1());
assertSame(app,customer.getApplication2());
@SuppressWarnings("unchecked") ThreadLocalProxy proxy=(ThreadLocalProxy)app.getUriInfo();
assertNotNull(proxy);
invokeCustomerMethod(sf.getServiceFactory().getClassResourceInfo().get(0),customer,server);
assertSame(app,customer.getApplication2());
assertTrue(proxy.get() instanceof UriInfo);
}
InternalCallVerifier IdentityVerifier
@Test public void testPerRequestContextFields() throws Exception {
ClassResourceInfo cri=new ClassResourceInfo(Customer.class,true);
cri.setResourceProvider(new PerRequestResourceProvider(Customer.class));
OperationResourceInfo ori=new OperationResourceInfo(Customer.class.getMethod("postConstruct",new Class[]{}),cri);
Customer c=new Customer();
Message m=createMessage();
m.put(Message.PROTOCOL_HEADERS,new HashMap>());
HttpServletResponse response=EasyMock.createMock(HttpServletResponse.class);
m.put(AbstractHTTPDestination.HTTP_RESPONSE,response);
InjectionUtils.injectContextFields(c,ori.getClassResourceInfo(),m);
assertSame(UriInfoImpl.class,c.getUriInfo2().getClass());
assertSame(HttpHeadersImpl.class,c.getHeaders().getClass());
assertSame(RequestImpl.class,c.getRequest().getClass());
assertSame(SecurityContextImpl.class,c.getSecurityContext().getClass());
assertSame(ProvidersImpl.class,c.getBodyWorkers().getClass());
}
BooleanVerifier InternalCallVerifier
@Test public void testIntersectMimeTypesCompositeSubtype7() throws Exception {
Message m=new MessageImpl();
m.put(JAXRSUtils.PARTIAL_HIERARCHICAL_MEDIA_SUBTYPE_CHECK,true);
assertTrue(JAXRSUtils.compareCompositeSubtypes("application/xml","application/bar+xml",m));
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@SuppressWarnings("unchecked") @Test public void testHttpContextParameters() throws Exception {
ClassResourceInfo cri=new ClassResourceInfo(Customer.class,true);
OperationResourceInfo ori=new OperationResourceInfo(Customer.class.getMethod("testParams",new Class[]{UriInfo.class,HttpHeaders.class,Request.class,SecurityContext.class,Providers.class,String.class,List.class}),cri);
ori.setHttpMethod("GET");
MultivaluedMap headers=new MetadataMap();
headers.add("Foo","bar, baz");
Message m=createMessage();
m.put("org.apache.cxf.http.header.split","true");
m.put(Message.PROTOCOL_HEADERS,headers);
List params=JAXRSUtils.processParameters(ori,new MetadataMap(),m);
assertEquals("7 parameters expected",7,params.size());
assertSame(UriInfoImpl.class,params.get(0).getClass());
assertSame(HttpHeadersImpl.class,params.get(1).getClass());
assertSame(RequestImpl.class,params.get(2).getClass());
assertSame(SecurityContextImpl.class,params.get(3).getClass());
assertSame(ProvidersImpl.class,params.get(4).getClass());
assertSame(String.class,params.get(5).getClass());
assertEquals("Wrong header param","bar",params.get(5));
List values=(List)params.get(6);
assertEquals("Wrong headers size",2,values.size());
assertEquals("Wrong 1st header param","bar",values.get(0));
assertEquals("Wrong 2nd header param","baz",values.get(1));
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testFromStringParameters() throws Exception {
Class>[] argType={UUID.class,CustomerGender.class,CustomerGender.class};
Method m=Customer.class.getMethod("testFromStringParam",argType);
UUID u=UUID.randomUUID();
Message messageImpl=createMessage();
messageImpl.put(Message.QUERY_STRING,"p1=" + u.toString() + "&p2=1&p3=2");
List params=JAXRSUtils.processParameters(new OperationResourceInfo(m,new ClassResourceInfo(Customer.class)),null,messageImpl);
assertEquals(3,params.size());
assertEquals("Query UUID Parameter was not matched correctly",u.toString(),params.get(0).toString());
assertSame(CustomerGender.FEMALE,params.get(1));
assertSame(CustomerGender.MALE,params.get(2));
}
InternalCallVerifier EqualityVerifier
@Test public void testParamAnnotationOnField() throws Exception {
ClassResourceInfo cri=new ClassResourceInfo(Customer.class,true);
Customer c=new Customer();
OperationResourceInfo ori=new OperationResourceInfo(Customer.class.getMethods()[0],cri);
Message m=createMessage();
MultivaluedMap headers=new MetadataMap();
headers.add("AHeader","theAHeader");
m.put(Message.PROTOCOL_HEADERS,headers);
m.put(Message.QUERY_STRING,"b=bValue");
JAXRSUtils.injectParameters(ori,c,m);
assertEquals("bValue",c.getB());
assertEquals("theAHeader",c.getAHeader());
}
UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testWrongType() throws Exception {
Class>[] argType={HashMap.class};
Method m=Customer.class.getMethod("testWrongType",argType);
Message messageImpl=createMessage();
messageImpl.put(Message.QUERY_STRING,"p1=1");
try {
JAXRSUtils.processParameters(new OperationResourceInfo(m,new ClassResourceInfo(Customer.class)),null,messageImpl);
fail("HashMap can not be handled as parameter");
}
catch ( WebApplicationException ex) {
assertEquals(500,ex.getResponse().getStatus());
assertEquals("Parameter Class java.util.HashMap has no constructor with " + "single String parameter, static valueOf(String) or fromString(String) methods",ex.getResponse().getEntity().toString());
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testFindTargetResourceClassWithTemplates() throws Exception {
JAXRSServiceFactoryBean sf=new JAXRSServiceFactoryBean();
sf.setResourceClasses(org.apache.cxf.jaxrs.resources.BookStoreTemplates.class);
sf.create();
List resources=((JAXRSServiceImpl)sf.getService()).getClassResourceInfos();
String contentTypes="*/*";
MetadataMap values=new MetadataMap();
OperationResourceInfo ori=findTargetResourceClass(resources,createMessage2(),"/1/2/","GET",values,contentTypes,getTypes("*/*"));
assertNotNull(ori);
assertEquals("getBooks",ori.getMethodToInvoke().getName());
assertEquals("Only id and final match groups should be there",2,values.size());
assertEquals("2 {id} values should've been picked up",2,values.get("id").size());
assertEquals("FINAL_MATCH_GROUP should've been picked up",1,values.get(URITemplate.FINAL_MATCH_GROUP).size());
assertEquals("First {id} is 1","1",values.getFirst("id"));
assertEquals("Second id is 2","2",values.get("id").get(1));
values=new MetadataMap();
ori=findTargetResourceClass(resources,createMessage2(),"/2","POST",values,contentTypes,getTypes("*/*"));
assertNotNull(ori);
assertEquals("updateBookStoreInfo",ori.getMethodToInvoke().getName());
assertEquals("Only id and final match groups should be there",2,values.size());
assertEquals("Only single {id} should've been picked up",1,values.get("id").size());
assertEquals("FINAL_MATCH_GROUP should've been picked up",1,values.get(URITemplate.FINAL_MATCH_GROUP).size());
assertEquals("Only the first {id} should've been picked up","2",values.getFirst("id"));
values=new MetadataMap();
ori=findTargetResourceClass(resources,createMessage2(),"/3/4","PUT",values,contentTypes,getTypes("*/*"));
assertNotNull(ori);
assertEquals("updateBook",ori.getMethodToInvoke().getName());
assertEquals("Only the first {id} should've been picked up",3,values.size());
assertEquals("Only the first {id} should've been picked up",1,values.get("id").size());
assertEquals("Only the first {id} should've been picked up",1,values.get("bookId").size());
assertEquals("Only the first {id} should've been picked up",1,values.get(URITemplate.FINAL_MATCH_GROUP).size());
assertEquals("Only the first {id} should've been picked up","3",values.getFirst("id"));
assertEquals("Only the first {id} should've been picked up","4",values.getFirst("bookId"));
}
BooleanVerifier InternalCallVerifier
@Test public void testIntersectMimeTypesCompositeSubtype9() throws Exception {
Message m=new MessageImpl();
m.put(JAXRSUtils.PARTIAL_HIERARCHICAL_MEDIA_SUBTYPE_CHECK,true);
assertTrue(JAXRSUtils.compareCompositeSubtypes("application/xml","application/xml+bar",m));
}
Class: org.apache.cxf.jaxrs.utils.ResourceUtilsTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testClassResourceInfoUserResource() throws Exception {
UserResource ur=new UserResource();
ur.setName(HashMap.class.getName());
ur.setPath("/hashmap");
UserOperation op=new UserOperation();
op.setPath("/key/{id}");
op.setName("get");
op.setVerb("POST");
op.setParameters(Collections.singletonList(new Parameter(ParameterType.PATH,"id")));
ur.setOperations(Collections.singletonList(op));
Map resources=new HashMap();
resources.put(ur.getName(),ur);
ClassResourceInfo cri=ResourceUtils.createClassResourceInfo(resources,ur,null,true,true,BusFactory.getDefaultBus());
assertNotNull(cri);
assertEquals("/hashmap",cri.getURITemplate().getValue());
Method method=HashMap.class.getMethod("get",new Class[]{Object.class});
OperationResourceInfo ori=cri.getMethodDispatcher().getOperationResourceInfo(method);
assertNotNull(ori);
assertEquals("/key/{id}",ori.getURITemplate().getValue());
List params=ori.getParameters();
assertNotNull(params);
Parameter p=params.get(0);
assertEquals("id",p.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testClassResourceInfoWithOverride() throws Exception {
ClassResourceInfo cri=ResourceUtils.createClassResourceInfo(ExampleImpl.class,ExampleImpl.class,true,true);
assertNotNull(cri);
Method m=ExampleImpl.class.getMethod("get");
OperationResourceInfo ori=cri.getMethodDispatcher().getOperationResourceInfo(m);
assertNotNull(ori);
assertEquals("GET",ori.getHttpMethod());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testUserResourceFromFile() throws Exception {
List list=ResourceUtils.getUserResources("classpath:/resources.xml");
assertNotNull(list);
assertEquals(1,list.size());
UserResource resource=list.get(0);
assertEquals("java.util.Map",resource.getName());
assertEquals("map",resource.getPath());
assertEquals("application/xml",resource.getProduces());
assertEquals("application/json",resource.getConsumes());
UserOperation oper=resource.getOperations().get(0);
assertEquals("putAll",oper.getName());
assertEquals("/putAll",oper.getPath());
assertEquals("PUT",oper.getVerb());
assertEquals("application/json",oper.getProduces());
assertEquals("application/xml",oper.getConsumes());
Parameter p=oper.getParameters().get(0);
assertEquals("map",p.getName());
assertEquals("emptyMap",p.getDefaultValue());
assertTrue(p.isEncoded());
assertEquals("REQUEST_BODY",p.getType().toString());
}
Class: org.apache.cxf.jaxws.CodeFirstTest InternalCallVerifier EqualityVerifier
@Test public void testRpcClient() throws Exception {
SayHiImpl serviceImpl=new SayHiImpl();
try (EndpointImpl ep=new EndpointImpl(getBus(),serviceImpl,(String)null)){
ep.publish("local://localhost:9090/hello");
QName serviceName=new QName("http://mynamespace.com/","SayHiService");
QName portName=new QName("http://mynamespace.com/","HelloPort");
ServiceImpl service=new ServiceImpl(getBus(),(URL)null,serviceName,null);
service.addPort(portName,"http://schemas.xmlsoap.org/soap/","local://localhost:9090/hello");
SayHi proxy=service.getPort(portName,SayHi.class);
long res=proxy.sayHi(3);
assertEquals(3,res);
String[] strInput=new String[2];
strInput[0]="Hello";
strInput[1]="Bonjour";
String[] strings=proxy.getStringArray(strInput);
assertEquals(strings.length,2);
assertEquals(strings[0],"HelloHello");
assertEquals(strings[1],"BonjourBonjour");
}
}
InternalCallVerifier EqualityVerifier
@Test public void testCXF1510() throws Exception {
JaxWsServerFactoryBean factory=new JaxWsServerFactoryBean();
factory.setServiceClass(NoRootBare.class);
factory.setServiceBean(new NoRootBareImpl());
factory.setAddress("local://localhost/testNoRootBare");
Server server=factory.create();
server.start();
QName serviceName=new QName("http://service.jaxws.cxf.apache.org/","NoRootBareService");
QName portName=new QName("http://service.jaxws.cxf.apache.org/","NoRootBarePort");
ServiceImpl service=new ServiceImpl(getBus(),(URL)null,serviceName,null);
service.addPort(portName,"http://schemas.xmlsoap.org/soap/","local://localhost/testNoRootBare");
NoRootBare proxy=service.getPort(portName,NoRootBare.class);
assertEquals("hello",proxy.echoString(new NoRootRequest("hello")).getMessage());
}
InternalCallVerifier EqualityVerifier
@Test public void testCXF1758() throws Exception {
JaxWsServerFactoryBean factory=new JaxWsServerFactoryBean();
factory.setServiceBean(new GenericsService2Impl());
factory.setAddress("local://localhost/test");
Server server=null;
server=factory.create();
Document doc=getWSDLDocument(server);
assertXPathEquals("//xsd:schema/xsd:complexType[@name='convert']/xsd:sequence/xsd:element/@type",Constants.XSD_INT,doc);
factory=new JaxWsServerFactoryBean();
factory.setServiceBean(new GenericsService2(){
public Double convert( Float t){
return t.doubleValue();
}
public GenericsService2.Value convert2( GenericsService2.Value in){
return new GenericsService2.Value(in.getValue().doubleValue());
}
}
);
factory.setAddress("local://localhost/test2");
server=factory.create();
Document doc2=getWSDLDocument(server);
assertXPathEquals("//xsd:schema/xsd:complexType[@name='convert']/xsd:sequence/" + "xsd:element/@type",Constants.XSD_FLOAT,doc2);
QName serviceName=new QName("http://service.jaxws.cxf.apache.org/","Generics2");
QName portName=new QName("http://service.jaxws.cxf.apache.org/","Generics2Port");
ServiceImpl service=new ServiceImpl(getBus(),(URL)null,serviceName,null);
service.addPort(portName,"http://schemas.xmlsoap.org/soap/","local://localhost/test2");
GenericsService2Typed proxy=service.getPort(portName,GenericsService2Typed.class);
assertEquals("",3.14d,proxy.convert(3.14f),0.00001);
assertEquals("",3.14d,proxy.convert2(new GenericsService2.Value(3.14f)).getValue(),0.00001);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testClient() throws Exception {
Hello serviceImpl=new Hello();
try (EndpointImpl ep=new EndpointImpl(getBus(),serviceImpl,(String)null)){
ep.publish("local://localhost:9090/hello");
QName serviceName=new QName("http://service.jaxws.cxf.apache.org/","HelloService");
QName portName=new QName("http://service.jaxws.cxf.apache.org/","HelloPort");
ServiceImpl service=new ServiceImpl(getBus(),(URL)null,serviceName,null);
service.addPort(portName,"http://schemas.xmlsoap.org/soap/","local://localhost:9090/hello");
HelloInterface proxy=service.getPort(portName,HelloInterface.class,new LoggingFeature());
Client client=ClientProxy.getClient(proxy);
boolean found=false;
for ( Interceptor extends Message> i : client.getOutInterceptors()) {
if (i instanceof LoggingOutInterceptor) {
found=true;
}
}
assertTrue(found);
assertEquals("Get the wrong result","hello",proxy.sayHi("hello"));
String[] strInput=new String[2];
strInput[0]="Hello";
strInput[1]="Bonjour";
String[] strings=proxy.getStringArray(strInput);
assertEquals(strings.length,2);
assertEquals(strings[0],"HelloHello");
assertEquals(strings[1],"BonjourBonjour");
List listInput=new ArrayList();
listInput.add("Hello");
listInput.add("Bonjour");
List list=proxy.getStringList(listInput);
assertEquals(list.size(),2);
assertEquals(list.get(0),"HelloHello");
assertEquals(list.get(1),"BonjourBonjour");
List result=proxy.getGreetings();
assertEquals(2,result.size());
}
}
UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testException() throws Exception {
Hello serviceImpl=new Hello();
try (EndpointImpl ep=new EndpointImpl(getBus(),serviceImpl,(String)null)){
ep.publish("local://localhost:9090/hello");
ep.getServer().getEndpoint().getInInterceptors().add(new LoggingInInterceptor());
ep.getServer().getEndpoint().getOutInterceptors().add(new LoggingOutInterceptor());
QName serviceName=new QName("http://service.jaxws.cxf.apache.org/","HelloService");
QName portName=new QName("http://service.jaxws.cxf.apache.org/","HelloPort");
ServiceImpl service=new ServiceImpl(getBus(),(URL)null,serviceName,null);
service.addPort(portName,"http://schemas.xmlsoap.org/soap/","local://localhost:9090/hello");
HelloInterface proxy=service.getPort(portName,HelloInterface.class);
ClientProxy.getClient(proxy).getInFaultInterceptors().add(new LoggingInInterceptor());
ClientProxy.getClient(proxy).getInInterceptors().add(new LoggingInInterceptor());
try {
proxy.addNumbers(1,-2);
fail("should throw AddNumbersException");
}
catch ( AddNumbersException e) {
assertEquals(e.getInfo(),"Sum is less than 0.");
}
try {
proxy.addNumbers(1,99);
fail("should throw AddNumbersSubException");
}
catch ( AddNumbersSubException e) {
assertEquals(e.getSubInfo(),"Sum is 100");
}
catch ( AddNumbersException e) {
fail("should throw AddNumbersSubException");
}
try (AutoCloseable c=(AutoCloseable)proxy){
assertEquals("Result = 2",proxy.addNumbers(1,1));
}
try {
proxy.addNumbers(1,1);
fail("Proxy should be closed");
}
catch ( IllegalStateException t) {
}
}
}
InternalCallVerifier EqualityVerifier
@Test public void testArrayAndList() throws Exception {
ArrayServiceImpl serviceImpl=new ArrayServiceImpl();
try (EndpointImpl ep=new EndpointImpl(getBus(),serviceImpl,(String)null)){
ep.publish("local://localhost:9090/array");
ep.getServer().getEndpoint().getInInterceptors().add(new LoggingInInterceptor());
ep.getServer().getEndpoint().getOutInterceptors().add(new LoggingOutInterceptor());
QName serviceName=new QName("http://service.jaxws.cxf.apache.org/","ArrayService");
QName portName=new QName("http://service.jaxws.cxf.apache.org/","ArrayPort");
ServiceImpl service=new ServiceImpl(getBus(),(URL)null,serviceName,null);
service.addPort(portName,"http://schemas.xmlsoap.org/soap/","local://localhost:9090/array");
ArrayService proxy=service.getPort(portName,ArrayService.class);
String[] arrayOut=proxy.arrayOutput();
assertEquals(arrayOut.length,3);
assertEquals(arrayOut[0],"string1");
assertEquals(arrayOut[1],"string2");
assertEquals(arrayOut[2],"string3");
String[] arrayIn=new String[3];
arrayIn[0]="string1";
arrayIn[1]="string2";
arrayIn[2]="string3";
assertEquals(proxy.arrayInput(arrayIn),"string1string2string3");
arrayOut=proxy.arrayInputAndOutput(arrayIn);
assertEquals(arrayOut.length,3);
assertEquals(arrayOut[0],"string11");
assertEquals(arrayOut[1],"string22");
assertEquals(arrayOut[2],"string33");
List listOut=proxy.listOutput();
assertEquals(listOut.size(),3);
assertEquals(listOut.get(0),"string1");
assertEquals(listOut.get(1),"string2");
assertEquals(listOut.get(2),"string3");
List listIn=new ArrayList();
listIn.add("list1");
listIn.add("list2");
listIn.add("list3");
assertEquals(proxy.listInput(listIn),"list1list2list3");
}
}
Class: org.apache.cxf.jaxws.CodeFirstWSDLTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testWSDL1() throws Exception {
Definition d=createService(Hello2.class);
QName serviceName=new QName("http://service.jaxws.cxf.apache.org/","Hello2Service");
javax.wsdl.Service service=d.getService(serviceName);
assertNotNull(service);
QName portName=new QName("http://service.jaxws.cxf.apache.org/","Hello2Port");
javax.wsdl.Port port=service.getPort(portName.getLocalPart());
assertNotNull(port);
QName portTypeName=new QName("http://service.jaxws.cxf.apache.org/","HelloInterface");
javax.wsdl.PortType portType=d.getPortType(portTypeName);
assertNotNull(portType);
assertEquals(5,portType.getOperations().size());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testWSDL2() throws Exception {
Definition d=createService(Hello3.class);
QName serviceName=new QName("http://mynamespace.com/","MyService");
javax.wsdl.Service service=d.getService(serviceName);
assertNotNull(service);
QName portName=new QName("http://mynamespace.com/","MyPort");
javax.wsdl.Port port=service.getPort(portName.getLocalPart());
assertNotNull(port);
QName portTypeName=new QName("http://service.jaxws.cxf.apache.org/","HelloInterface");
javax.wsdl.PortType portType=d.getPortType(portTypeName);
assertNotNull(portType);
assertEquals(5,portType.getOperations().size());
}
Class: org.apache.cxf.jaxws.EndpointImplTest BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testEndpointServiceConstructor() throws Exception {
GreeterImpl greeter=new GreeterImpl();
JaxWsServiceFactoryBean serviceFactory=new JaxWsServiceFactoryBean();
serviceFactory.setBus(getBus());
serviceFactory.setInvoker(new BeanInvoker(greeter));
serviceFactory.setServiceClass(GreeterImpl.class);
try (EndpointImpl endpoint=new EndpointImpl(getBus(),greeter,new JaxWsServerFactoryBean(serviceFactory))){
WebServiceContext ctx=greeter.getContext();
assertNull(ctx);
try {
String address="http://localhost:8080/test";
endpoint.publish(address);
}
catch ( IllegalArgumentException ex) {
assertTrue(ex.getCause() instanceof BusException);
assertEquals("BINDING_INCOMPATIBLE_ADDRESS_EXC",((BusException)ex.getCause()).getCode());
}
ctx=greeter.getContext();
assertNotNull(ctx);
}
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testAddWSAFeature() throws Exception {
GreeterImpl greeter=new GreeterImpl();
JaxWsServiceFactoryBean serviceFactory=new JaxWsServiceFactoryBean();
serviceFactory.setBus(getBus());
serviceFactory.setInvoker(new BeanInvoker(greeter));
serviceFactory.setServiceClass(GreeterImpl.class);
try (EndpointImpl endpoint=new EndpointImpl(getBus(),greeter,new JaxWsServerFactoryBean(serviceFactory))){
endpoint.getFeatures().add(new WSAddressingFeature());
try {
String address="http://localhost:8080/test";
endpoint.publish(address);
}
catch ( IllegalArgumentException ex) {
assertTrue(ex.getCause() instanceof BusException);
assertEquals("BINDING_INCOMPATIBLE_ADDRESS_EXC",((BusException)ex.getCause()).getCode());
}
assertTrue(serviceFactory.getFeatures().size() == 1);
assertTrue(serviceFactory.getFeatures().get(0) instanceof WSAddressingFeature);
}
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testJaxWsaFeature() throws Exception {
HelloWsa greeter=new HelloWsa();
JaxWsServiceFactoryBean serviceFactory=new JaxWsServiceFactoryBean();
serviceFactory.setBus(getBus());
serviceFactory.setInvoker(new BeanInvoker(greeter));
serviceFactory.setServiceClass(HelloWsa.class);
try (EndpointImpl endpoint=new EndpointImpl(getBus(),greeter,new JaxWsServerFactoryBean(serviceFactory))){
try {
String address="http://localhost:8080/test";
endpoint.publish(address);
}
catch ( IllegalArgumentException ex) {
assertTrue(ex.getCause() instanceof BusException);
assertEquals("BINDING_INCOMPATIBLE_ADDRESS_EXC",((BusException)ex.getCause()).getCode());
}
assertEquals(1,serviceFactory.getFeatures().size());
assertTrue(serviceFactory.getFeatures().get(0) instanceof WSAddressingFeature);
}
}
UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testEndpoint() throws Exception {
String address="http://localhost:8080/test";
GreeterImpl greeter=new GreeterImpl();
try (EndpointImpl endpoint=new EndpointImpl(getBus(),greeter,(String)null)){
WebServiceContext ctx=greeter.getContext();
assertNull(ctx);
try {
endpoint.publish(address);
}
catch ( IllegalArgumentException ex) {
assertTrue(ex.getCause() instanceof BusException);
assertEquals("BINDING_INCOMPATIBLE_ADDRESS_EXC",((BusException)ex.getCause()).getCode());
}
ctx=greeter.getContext();
assertNotNull(ctx);
try {
endpoint.publish(address);
fail("republished an already published endpoint.");
}
catch ( IllegalStateException e) {
}
try {
endpoint.setMetadata(new ArrayList(0));
fail("set metadata on an already published endpoint.");
}
catch ( IllegalStateException e) {
}
}
}
UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testEndpointStop() throws Exception {
String address="http://localhost:8080/test";
GreeterImpl greeter=new GreeterImpl();
try (EndpointImpl endpoint=new EndpointImpl(getBus(),greeter,(String)null)){
WebServiceContext ctx=greeter.getContext();
assertNull(ctx);
try {
endpoint.publish(address);
}
catch ( IllegalArgumentException ex) {
assertTrue(ex.getCause() instanceof BusException);
assertEquals("BINDING_INCOMPATIBLE_ADDRESS_EXC",((BusException)ex.getCause()).getCode());
}
ctx=greeter.getContext();
assertNotNull(ctx);
assertTrue(endpoint.isPublished());
endpoint.stop();
assertFalse(endpoint.isPublished());
try {
endpoint.publish(address);
fail("stopped endpoint restarted.");
}
catch ( IllegalStateException e) {
}
}
}
Class: org.apache.cxf.jaxws.EndpointReferenceTest APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testBindingProviderSOAPBindingStaicService() throws Exception {
org.apache.hello_world_soap_http.SOAPService s=new org.apache.hello_world_soap_http.SOAPService();
Greeter greeter=s.getPort(Greeter.class);
BindingProvider bindingProvider=(BindingProvider)greeter;
EndpointReference er=bindingProvider.getEndpointReference();
assertNotNull(er);
assertTrue(er instanceof W3CEndpointReference);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testEndpointReferenceGetPort() throws Exception {
BusFactory.setDefaultBus(getBus());
GreeterImpl greeter1=new GreeterImpl();
try (EndpointImpl endpoint=new EndpointImpl(getBus(),greeter1,(String)null)){
endpoint.publish("http://localhost:8080/test");
InputStream is=getClass().getResourceAsStream("resources/hello_world_soap_http_infoset.xml");
Document doc=StaxUtils.read(is);
DOMSource erXML=new DOMSource(doc);
EndpointReference endpointReference=EndpointReference.readFrom(erXML);
WebServiceFeature[] wfs=new WebServiceFeature[]{};
Greeter greeter=endpointReference.getPort(Greeter.class,wfs);
String response=greeter.greetMe("John");
assertEquals("Hello John",response);
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testServiceGetPortUsingEndpointReference() throws Exception {
BusFactory.setDefaultBus(getBus());
GreeterImpl greeter1=new GreeterImpl();
try (EndpointImpl endpoint=new EndpointImpl(getBus(),greeter1,(String)null)){
endpoint.publish("http://localhost:8080/test");
javax.xml.ws.Service s=javax.xml.ws.Service.create(new QName("http://apache.org/hello_world_soap_http","SoapPort"));
InputStream is=getClass().getResourceAsStream("resources/hello_world_soap_http_infoset.xml");
Document doc=StaxUtils.read(is);
DOMSource erXML=new DOMSource(doc);
EndpointReference endpointReference=EndpointReference.readFrom(erXML);
WebServiceFeature[] wfs=new WebServiceFeature[]{};
Greeter greeter=s.getPort(endpointReference,Greeter.class,wfs);
String response=greeter.greetMe("John");
assertEquals("Hello John",response);
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testProviderReadEndpointReference() throws Exception {
ProviderImpl provider=new ProviderImpl();
InputStream is=getClass().getResourceAsStream("resources/hello_world_soap_http_infoset.xml");
Document doc=StaxUtils.read(is);
DOMSource erXML=new DOMSource(doc);
EndpointReference endpointReference=provider.readEndpointReference(erXML);
assertNotNull(endpointReference);
assertTrue(endpointReference instanceof W3CEndpointReference);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testEndpointGetEndpointReferenceSOAPBinding() throws Exception {
GreeterImpl greeter=new GreeterImpl();
try (EndpointImpl endpoint=new EndpointImpl(getBus(),greeter,(String)null)){
endpoint.publish("http://localhost:8080/test");
InputStream is=getClass().getResourceAsStream("resources/hello_world_soap_http_infoset.xml");
Document doc=StaxUtils.read(is);
Element referenceParameters=fetchElementByNameAttribute(doc.getDocumentElement(),"wsa:ReferenceParameters","");
EndpointReference endpointReference=endpoint.getEndpointReference(referenceParameters);
assertNotNull(endpointReference);
assertTrue(endpointReference instanceof W3CEndpointReference);
endpoint.stop();
}
}
InternalCallVerifier NullVerifier
@Test public void testProviderCreateW3CEndpointReference() throws Exception {
ProviderImpl provider=new ProviderImpl();
InputStream is=getClass().getResourceAsStream("resources/hello_world_soap_http_infoset.xml");
Document doc=StaxUtils.read(is);
Element referenceParameter=fetchElementByNameAttribute(doc.getDocumentElement(),"wsa:ReferenceParameters","");
List referenceParameters=new ArrayList();
if (referenceParameter != null) {
referenceParameters.add(referenceParameter);
}
Element metadata=fetchElementByNameAttribute(doc.getDocumentElement(),"wsa:metadata","");
List metadataList=new ArrayList();
if (metadata != null) {
metadataList.add(metadata);
}
W3CEndpointReference endpointReference=provider.createW3CEndpointReference("http://localhost:8080/test",serviceName,portName,metadataList,"wsdlDocumentLocation",referenceParameters);
assertNotNull(endpointReference);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testEndpointGetEndpointReferenceW3C() throws Exception {
GreeterImpl greeter=new GreeterImpl();
try (EndpointImpl endpoint=new EndpointImpl(getBus(),greeter,(String)null)){
endpoint.publish("http://localhost:8080/test");
InputStream is=getClass().getResourceAsStream("resources/hello_world_soap_http_infoset.xml");
Document doc=StaxUtils.read(is);
Element referenceParameters=fetchElementByNameAttribute(doc.getDocumentElement(),"wsa:ReferenceParameters","");
EndpointReference endpointReference=endpoint.getEndpointReference(W3CEndpointReference.class,referenceParameters);
assertNotNull(endpointReference);
assertTrue(endpointReference instanceof W3CEndpointReference);
endpoint.stop();
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testProviderGetPort() throws Exception {
BusFactory.setDefaultBus(getBus());
GreeterImpl greeter1=new GreeterImpl();
try (EndpointImpl endpoint=new EndpointImpl(getBus(),greeter1,(String)null)){
endpoint.publish("http://localhost:8080/test");
ProviderImpl provider=new ProviderImpl();
InputStream is=getClass().getResourceAsStream("resources/hello_world_soap_http_infoset.xml");
Document doc=StaxUtils.read(is);
DOMSource erXML=new DOMSource(doc);
EndpointReference endpointReference=EndpointReference.readFrom(erXML);
WebServiceFeature[] wfs=new WebServiceFeature[]{};
Greeter greeter=provider.getPort(endpointReference,Greeter.class,wfs);
String response=greeter.greetMe("John");
assertEquals("Hello John",response);
}
}
Class: org.apache.cxf.jaxws.GreeterTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testEndpoint() throws Exception {
ReflectionServiceFactoryBean bean=new JaxWsServiceFactoryBean();
URL resource=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(resource);
bean.setWsdlURL(resource.toString());
bean.setBus(bus);
bean.setServiceClass(GreeterImpl.class);
GreeterImpl greeter=new GreeterImpl();
BeanInvoker invoker=new BeanInvoker(greeter);
Service service=bean.create();
assertEquals("SOAPService",service.getName().getLocalPart());
assertEquals("http://apache.org/hello_world_soap_http",service.getName().getNamespaceURI());
ServerFactoryBean svr=new ServerFactoryBean();
svr.setBus(bus);
svr.setServiceFactory(bean);
svr.setInvoker(invoker);
svr.create();
Node response=invoke("http://localhost:9000/SoapContext/SoapPort",LocalTransportFactory.TRANSPORT_ID,"GreeterMessage.xml");
assertEquals(1,greeter.getInvocationCount());
assertNotNull(response);
addNamespace("h","http://apache.org/hello_world_soap_http/types");
assertValid("/s:Envelope/s:Body",response);
assertValid("//h:sayHiResponse",response);
}
Class: org.apache.cxf.jaxws.HeaderTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testInvocation() throws Exception {
JaxWsServiceFactoryBean bean=new JaxWsServiceFactoryBean();
Bus bus=getBus();
bean.setBus(bus);
bean.setServiceClass(TestHeaderImpl.class);
Service service=bean.create();
OperationInfo op=service.getServiceInfos().get(0).getInterface().getOperation(new QName(service.getName().getNamespaceURI(),"testHeader5"));
assertNotNull(op);
List parts=op.getInput().getMessageParts();
assertEquals(1,parts.size());
MessagePartInfo part=parts.get(0);
assertNotNull(part.getTypeClass());
assertEquals(TestHeader5.class,part.getTypeClass());
parts=op.getOutput().getMessageParts();
assertEquals(2,parts.size());
part=parts.get(1);
assertNotNull(part.getTypeClass());
assertEquals(TestHeader5ResponseBody.class,part.getTypeClass());
part=parts.get(0);
assertNotNull(part.getTypeClass());
assertEquals(TestHeader5.class,part.getTypeClass());
ServerFactoryBean svr=new ServerFactoryBean();
svr.setBus(bus);
svr.setServiceFactory(bean);
svr.setServiceBean(new TestHeaderImpl());
svr.setAddress("http://localhost:9104/SoapHeaderContext/SoapHeaderPort");
svr.setBindingConfig(new JaxWsSoapBindingConfiguration(bean));
svr.create();
Node response=invoke("http://localhost:9104/SoapHeaderContext/SoapHeaderPort",LocalTransportFactory.TRANSPORT_ID,"testHeader5.xml");
assertNotNull(response);
assertNoFault(response);
addNamespace("t","http://apache.org/header_test/types");
assertValid("//s:Header/t:testHeader5",response);
}
Class: org.apache.cxf.jaxws.JAXWSMethodInvokerTest UtilityVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testFaultAvoidHeadersCopy() throws Throwable {
ExceptionService serviceObject=new ExceptionService();
Method serviceMethod=ExceptionService.class.getMethod("invoke",new Class[]{});
Exchange ex=new ExchangeImpl();
prepareInMessage(ex,false);
JAXWSMethodInvoker jaxwsMethodInvoker=prepareJAXWSMethodInvoker(ex,serviceObject,serviceMethod);
try {
jaxwsMethodInvoker.invoke(ex,new MessageContentsList(new Object[]{}));
fail("Expected fault");
}
catch ( Fault fault) {
Message outMsg=ex.getOutMessage();
Assert.assertNull(outMsg);
}
}
UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testFaultHeadersCopy() throws Throwable {
ExceptionService serviceObject=new ExceptionService();
Method serviceMethod=ExceptionService.class.getMethod("invoke",new Class[]{});
Exchange ex=new ExchangeImpl();
prepareInMessage(ex,true);
Message msg=new MessageImpl();
SoapMessage outMessage=new SoapMessage(msg);
ex.setOutMessage(outMessage);
JAXWSMethodInvoker jaxwsMethodInvoker=prepareJAXWSMethodInvoker(ex,serviceObject,serviceMethod);
try {
jaxwsMethodInvoker.invoke(ex,new MessageContentsList(new Object[]{}));
fail("Expected fault");
}
catch ( Fault fault) {
Message outMsg=ex.getOutMessage();
Assert.assertNotNull(outMsg);
@SuppressWarnings("unchecked") List headers=(List)outMsg.get(Header.HEADER_LIST);
Assert.assertEquals(1,headers.size());
Assert.assertEquals(TEST_HEADER_NAME,headers.get(0).getName());
}
}
InternalCallVerifier EqualityVerifier
@Test public void testFactoryBeans() throws Throwable {
Exchange ex=EasyMock.createMock(Exchange.class);
EasyMock.reset(factory);
factory.create(ex);
EasyMock.expectLastCall().andReturn(target);
EasyMock.replay(factory);
JAXWSMethodInvoker jaxwsMethodInvoker=new JAXWSMethodInvoker(factory);
Object object=jaxwsMethodInvoker.getServiceObject(ex);
assertEquals("the target object and service object should be equal ",object,target);
EasyMock.verify(factory);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testProviderInterpretNullAsOneway() throws Throwable {
NullableProviderService serviceObject=new NullableProviderService();
Method serviceMethod=NullableProviderService.class.getMethod("invoke",new Class[]{Source.class});
Exchange ex=new ExchangeImpl();
Message inMessage=new MessageImpl();
inMessage.setInterceptorChain(new PhaseInterceptorChain(new TreeSet()));
ex.setInMessage(inMessage);
inMessage.setExchange(ex);
inMessage.put(Message.REQUESTOR_ROLE,Boolean.TRUE);
JAXWSMethodInvoker jaxwsMethodInvoker=prepareJAXWSMethodInvoker(ex,serviceObject,serviceMethod);
ex.setOneWay(false);
MessageContentsList obj=(MessageContentsList)jaxwsMethodInvoker.invoke(ex,new MessageContentsList(new Object[]{new StreamSource()}));
assertEquals(1,obj.size());
assertNotNull(obj.get(0));
assertFalse(ex.isOneWay());
ex.setOneWay(true);
obj=(MessageContentsList)jaxwsMethodInvoker.invoke(ex,new MessageContentsList(new Object[]{new StreamSource()}));
assertNull(obj);
assertTrue(ex.isOneWay());
ex.setOneWay(false);
serviceObject.setNullable(true);
obj=(MessageContentsList)jaxwsMethodInvoker.invoke(ex,new MessageContentsList(new Object[]{new StreamSource()}));
assertNull(obj);
assertTrue(ex.isOneWay());
ex.setOneWay(false);
serviceObject.setNullable(true);
inMessage.put("jaxws.provider.interpretNullAsOneway",Boolean.FALSE);
obj=(MessageContentsList)jaxwsMethodInvoker.invoke(ex,new MessageContentsList(new Object[]{new StreamSource()}));
assertEquals(1,obj.size());
assertNull(obj.get(0));
assertFalse(ex.isOneWay());
ex.setOneWay(false);
serviceObject.setNullable(true);
inMessage.put("jaxws.provider.interpretNullAsOneway",Boolean.TRUE);
obj=(MessageContentsList)jaxwsMethodInvoker.invoke(ex,new MessageContentsList(new Object[]{new StreamSource()}));
assertNull(obj);
assertTrue(ex.isOneWay());
}
Class: org.apache.cxf.jaxws.JaxWsClientTest UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testEndpoint() throws Exception {
ReflectionServiceFactoryBean bean=new JaxWsServiceFactoryBean();
URL resource=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(resource);
bean.setWsdlURL(resource.toString());
bean.setBus(getBus());
bean.setServiceClass(GreeterImpl.class);
GreeterImpl greeter=new GreeterImpl();
BeanInvoker invoker=new BeanInvoker(greeter);
bean.setInvoker(invoker);
Service service=bean.create();
String namespace="http://apache.org/hello_world_soap_http";
EndpointInfo ei=service.getServiceInfos().get(0).getEndpoint(new QName(namespace,"SoapPort"));
JaxWsEndpointImpl endpoint=new JaxWsEndpointImpl(getBus(),service,ei);
ClientImpl client=new ClientImpl(getBus(),endpoint);
BindingOperationInfo bop=ei.getBinding().getOperation(new QName(namespace,"sayHi"));
assertNotNull(bop);
bop=bop.getUnwrappedOperation();
assertNotNull(bop);
MessagePartInfo part=bop.getOutput().getMessageParts().get(0);
assertEquals(0,part.getIndex());
d.setMessageObserver(new MessageReplayObserver("sayHiResponse.xml"));
Object ret[]=client.invoke(bop,new Object[]{"hi"},null);
assertNotNull(ret);
assertEquals("Wrong number of return objects",1,ret.length);
bop=ei.getBinding().getOperation(new QName(namespace,"testDocLitFault"));
bop=bop.getUnwrappedOperation();
d.setMessageObserver(new MessageReplayObserver("testDocLitFault.xml"));
try {
client.invoke(bop,new Object[]{"BadRecordLitFault"},null);
fail("Should have returned a fault!");
}
catch ( BadRecordLitFault fault) {
assertEquals("foo",fault.getFaultInfo().trim());
assertEquals("Hadrian did it.",fault.getMessage());
}
try {
client.getEndpoint().getOutInterceptors().add(new NestedFaultThrower());
client.getEndpoint().getOutInterceptors().add(new FaultThrower());
client.invoke(bop,new Object[]{"BadRecordLitFault"},null);
fail("Should have returned a fault!");
}
catch ( Fault fault) {
assertEquals(true,fault.getMessage().indexOf("Foo") >= 0);
}
}
InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testClientProxyFactory(){
JaxWsProxyFactoryBean cf=new JaxWsProxyFactoryBean();
cf.setAddress("http://localhost:9000/test");
Greeter greeter=cf.create(Greeter.class);
Greeter greeter2=(Greeter)cf.create();
Greeter greeter3=(Greeter)cf.create();
Client c=(Client)greeter;
Client c2=(Client)greeter2;
Client c3=(Client)greeter3;
assertNotSame(c,c2);
assertNotSame(c,c3);
assertNotSame(c3,c2);
assertNotSame(c.getEndpoint(),c2.getEndpoint());
assertNotSame(c.getEndpoint(),c3.getEndpoint());
assertNotSame(c3.getEndpoint(),c2.getEndpoint());
c3.getInInterceptors();
((BindingProvider)greeter).getRequestContext().put("test","manny");
((BindingProvider)greeter2).getRequestContext().put("test","moe");
((BindingProvider)greeter3).getRequestContext().put("test","jack");
assertEquals("manny",((BindingProvider)greeter).getRequestContext().get("test"));
assertEquals("moe",((BindingProvider)greeter2).getRequestContext().get("test"));
assertEquals("jack",((BindingProvider)greeter3).getRequestContext().get("test"));
}
Class: org.apache.cxf.jaxws.JaxWsServerFactoryBeanTest InternalCallVerifier NullVerifier
@Test public void testBean(){
JaxWsServerFactoryBean sf=new JaxWsServerFactoryBean();
sf.setBus(getBus());
sf.setAddress("http://localhost:9000/test");
sf.setServiceClass(Hello.class);
sf.setStart(false);
Server server=sf.create();
assertNotNull(server);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testJaxbExtraClass(){
JaxWsServerFactoryBean sf=new JaxWsServerFactoryBean();
sf.setBus(getBus());
sf.setAddress("http://localhost:9000/test");
sf.setServiceClass(Hello.class);
sf.setStart(false);
Map props=sf.getProperties();
if (props == null) {
props=new HashMap();
}
props.put("jaxb.additionalContextClasses",new Class[]{DescriptionType.class,DisplayNameType.class});
sf.setProperties(props);
Server server=sf.create();
assertNotNull(server);
Class>[] extraClass=((JAXBDataBinding)sf.getServiceFactory().getDataBinding()).getExtraClass();
assertEquals(extraClass.length,2);
assertEquals(extraClass[0],DescriptionType.class);
assertEquals(extraClass[1],DisplayNameType.class);
}
InternalCallVerifier NullVerifier
@Test public void testBareGreeter() throws Exception {
JaxWsServerFactoryBean sf=new JaxWsServerFactoryBean();
sf.setBus(getBus());
sf.setServiceClass(GreeterImplDoc.class);
sf.setStart(false);
Server server=sf.create();
assertNotNull(server);
}
InternalCallVerifier NullVerifier
@Test public void testJaxwsServiceClass() throws Exception {
JaxWsServerFactoryBean factory=new JaxWsServerFactoryBean();
factory.setServiceClass(CalculatorPortType.class);
factory.setServiceBean(new CalculatorImpl());
String address="http://localhost:9001/jaxwstest";
factory.setAddress(address);
Server server=factory.create();
Endpoint endpoint=server.getEndpoint();
ServiceInfo service=endpoint.getEndpointInfo().getService();
assertNotNull(service);
Bus bus=factory.getBus();
Definition def=new ServiceWSDLBuilder(bus,service).build();
WSDLWriter wsdlWriter=bus.getExtension(WSDLManager.class).getWSDLFactory().newWSDLWriter();
def.setExtensionRegistry(bus.getExtension(WSDLManager.class).getExtensionRegistry());
Document doc=wsdlWriter.getDocument(def);
Map ns=new HashMap();
ns.put("wsdl","http://schemas.xmlsoap.org/wsdl/");
ns.put("soap","http://schemas.xmlsoap.org/wsdl/soap/");
XPathUtils xpather=new XPathUtils(ns);
xpather.isExist("/wsdl:definitions/wsdl:binding/soap:binding",doc,XPathConstants.NODE);
xpather.isExist("/wsdl:definitions/wsdl:binding/wsdl:operation[@name='add']/soap:operation",doc,XPathConstants.NODE);
xpather.isExist("/wsdl:definitions/wsdl:service/wsdl:port[@name='add']/soap:address[@location='" + address + "']",doc,XPathConstants.NODE);
}
InternalCallVerifier NullVerifier
@Test public void testSimpleServiceClass() throws Exception {
ServerFactoryBean factory=new ServerFactoryBean();
factory.setServiceClass(Hello.class);
String address="http://localhost:9001/jaxwstest";
factory.setAddress(address);
Server server=factory.create();
Endpoint endpoint=server.getEndpoint();
ServiceInfo service=endpoint.getEndpointInfo().getService();
assertNotNull(service);
Bus bus=factory.getBus();
Definition def=new ServiceWSDLBuilder(bus,service).build();
WSDLWriter wsdlWriter=bus.getExtension(WSDLManager.class).getWSDLFactory().newWSDLWriter();
def.setExtensionRegistry(bus.getExtension(WSDLManager.class).getExtensionRegistry());
Document doc=wsdlWriter.getDocument(def);
Map ns=new HashMap();
ns.put("wsdl","http://schemas.xmlsoap.org/wsdl/");
ns.put("soap","http://schemas.xmlsoap.org/wsdl/soap/");
XPathUtils xpather=new XPathUtils(ns);
xpather.isExist("/wsdl:definitions/wsdl:binding/soap:binding",doc,XPathConstants.NODE);
xpather.isExist("/wsdl:definitions/wsdl:binding/wsdl:operation[@name='add']/soap:operation",doc,XPathConstants.NODE);
xpather.isExist("/wsdl:definitions/wsdl:service/wsdl:port[@name='add']/soap:address[@location='" + address + "']",doc,XPathConstants.NODE);
}
Class: org.apache.cxf.jaxws.SEIWithJAXBAnnoTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testXMLList() throws Exception {
AddNumbersImpl serviceImpl=new AddNumbersImpl();
Endpoint.publish("local://localhost:9000/Hello",serviceImpl);
JaxWsProxyFactoryBean factory=new JaxWsProxyFactoryBean();
factory.setBus(SpringBusFactory.getDefaultBus());
factory.setServiceClass(AddNumbers.class);
factory.setAddress(address);
AddNumbers proxy=(AddNumbers)factory.create();
StringWriter strWriter=new StringWriter();
LoggingOutInterceptor log=new LoggingOutInterceptor(new PrintWriter(strWriter));
ClientProxy.getClient(proxy).getOutInterceptors().add(log);
List args=new ArrayList();
args.add("str1");
args.add("str2");
args.add("str3");
List result=proxy.addNumbers(args);
String expected="str1 str2 str3 ";
assertTrue("Client does not use the generated wrapper class to marshal request parameters",strWriter.toString().indexOf(expected) > -1);
assertEquals("Get the wrong result",100,(int)result.get(0));
}
Class: org.apache.cxf.jaxws.SOAPBindingTest APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testSAAJ() throws Exception {
URL wsdl1=getClass().getResource("/wsdl/calculator.wsdl");
assertNotNull(wsdl1);
ServiceImpl service=new ServiceImpl(getBus(),wsdl1,SERVICE_1,ServiceImpl.class);
CalculatorPortType cal=service.getPort(PORT_1,CalculatorPortType.class);
BindingProvider bindingProvider=(BindingProvider)cal;
assertTrue(bindingProvider.getBinding() instanceof SOAPBinding);
SOAPBinding binding=(SOAPBinding)bindingProvider.getBinding();
assertNotNull(binding.getMessageFactory());
assertNotNull(binding.getSOAPFactory());
}
APIUtilityVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testRoles() throws Exception {
URL wsdl1=getClass().getResource("/wsdl/calculator.wsdl");
assertNotNull(wsdl1);
ServiceImpl service=new ServiceImpl(getBus(),wsdl1,SERVICE_1,ServiceImpl.class);
CalculatorPortType cal=service.getPort(PORT_1,CalculatorPortType.class);
BindingProvider bindingProvider=(BindingProvider)cal;
assertTrue(bindingProvider.getBinding() instanceof SOAPBinding);
SOAPBinding binding=(SOAPBinding)bindingProvider.getBinding();
assertNotNull(binding.getRoles());
assertEquals(2,binding.getRoles().size());
assertTrue(binding.getRoles().contains(Soap12.getInstance().getNextRole()));
assertTrue(binding.getRoles().contains(Soap12.getInstance().getUltimateReceiverRole()));
String myrole="http://myrole";
Set roles=new HashSet();
roles.add(myrole);
binding.setRoles(roles);
assertNotNull(binding.getRoles());
assertEquals(3,binding.getRoles().size());
assertTrue(binding.getRoles().contains(myrole));
assertTrue(binding.getRoles().contains(Soap12.getInstance().getNextRole()));
assertTrue(binding.getRoles().contains(Soap12.getInstance().getUltimateReceiverRole()));
roles.add(Soap12.getInstance().getNoneRole());
try {
binding.setRoles(roles);
fail("did not throw exception");
}
catch ( WebServiceException e) {
}
}
Class: org.apache.cxf.jaxws.SchemaFirstXmlConfigTest InternalCallVerifier NullVerifier
@Test public void testEndpoint() throws Exception {
JaxWsServerFactoryBean serverFB=(JaxWsServerFactoryBean)ctx.getBean("helloServer");
assertNotNull(serverFB.getServer());
Document d=getWSDLDocument(serverFB.getServer());
assertValid("//xsd:complexType[@name='foo']/xsd:sequence",d);
EndpointImpl ep=(EndpointImpl)ctx.getBean("helloEndpoint");
d=getWSDLDocument(ep.getServer());
assertValid("//xsd:complexType[@name='foo']/xsd:sequence",d);
}
Class: org.apache.cxf.jaxws.ServiceImplTest InternalCallVerifier NullVerifier
@Test public void testCreateDispatchGoodPort(){
URL wsdl1=getClass().getResource("/wsdl/calculator.wsdl");
assertNotNull(wsdl1);
ServiceImpl service=new ServiceImpl(getBus(),wsdl1,SERVICE_1,ServiceImpl.class);
Dispatch dispatch=service.createDispatch(PORT_1,Source.class,Service.Mode.PAYLOAD);
assertNotNull(dispatch);
}
InternalCallVerifier NullVerifier
@Test public void testGetGoodPort(){
URL wsdl1=getClass().getResource("/wsdl/calculator.wsdl");
assertNotNull(wsdl1);
ServiceImpl service=new ServiceImpl(getBus(),wsdl1,SERVICE_1,ServiceImpl.class);
CalculatorPortType cal=service.getPort(PORT_1,CalculatorPortType.class);
assertNotNull(cal);
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testPorts(){
URL wsdl1=getClass().getResource("/wsdl/calculator.wsdl");
assertNotNull(wsdl1);
ServiceImpl service=new ServiceImpl(getBus(),wsdl1,SERVICE_1,ServiceImpl.class);
Iterator iter=service.getPorts();
assertNotNull(iter);
assertTrue(iter.hasNext());
assertEquals(PORT_1,iter.next());
assertFalse(iter.hasNext());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testJAXBCachedOnRepeatGetPort(){
System.gc();
System.gc();
URL wsdl1=getClass().getResource("/wsdl/calculator.wsdl");
assertNotNull(wsdl1);
ServiceImpl service=new ServiceImpl(getBus(),wsdl1,SERVICE_1,ServiceImpl.class);
CalculatorPortType cal1=service.getPort(PORT_1,CalculatorPortType.class);
assertNotNull(cal1);
ClientProxy cp=(ClientProxy)Proxy.getInvocationHandler(cal1);
JAXBDataBinding db1=(JAXBDataBinding)cp.getClient().getEndpoint().getService().getDataBinding();
assertNotNull(db1);
System.gc();
System.gc();
System.gc();
System.gc();
CalculatorPortType cal2=service.getPort(PORT_1,CalculatorPortType.class);
assertNotNull(cal2);
cp=(ClientProxy)Proxy.getInvocationHandler(cal2);
JAXBDataBinding db2=(JAXBDataBinding)cp.getClient().getEndpoint().getService().getDataBinding();
assertNotNull(db2);
assertEquals("got cached JAXBContext",db1.getContext(),db2.getContext());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testHandlerResolver(){
URL wsdl1=getClass().getResource("/wsdl/calculator.wsdl");
assertNotNull(wsdl1);
ServiceImpl service=new ServiceImpl(getBus(),wsdl1,SERVICE_1,ServiceImpl.class);
TestHandlerResolver resolver=new TestHandlerResolver();
assertNull(resolver.getPortInfo());
service.setHandlerResolver(resolver);
CalculatorPortType cal=service.getPort(PORT_1,CalculatorPortType.class);
assertNotNull(cal);
PortInfo info=resolver.getPortInfo();
assertNotNull(info);
assertEquals(SERVICE_1,info.getServiceName());
assertEquals(PORT_1,info.getPortName());
assertEquals(SOAPBinding.SOAP12HTTP_BINDING,info.getBindingID());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testServiceImpl() throws Exception {
SOAPService service=new SOAPService();
Greeter proxy=service.getSoapPort();
Client client=ClientProxy.getClient(proxy);
assertEquals("bar",client.getEndpoint().get("foo"));
assertNotNull("expected ConduitSelector",client.getConduitSelector());
assertTrue("unexpected ConduitSelector",client.getConduitSelector() instanceof NullConduitSelector);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testNonSpecificGetPort() throws Exception {
SOAPService service=new SOAPService();
Greeter proxy=service.getPort(Greeter.class);
Client client=ClientProxy.getClient(proxy);
boolean boolA=client.getEndpoint().getEndpointInfo().getName().equals(SOAP_PORT);
boolean boolB=client.getEndpoint().getEndpointInfo().getName().equals(SOAP_PORT1);
assertTrue(boolA || boolB);
assertNotNull("expected ConduitSelector",client.getConduitSelector());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test @SuppressWarnings("unchecked") public void testGetSOAP12BindingIDFromWSDL() throws Exception {
QName serviceName=new QName("http://apache.org/hello_world_soap12_http","SOAPService");
URL wsdlURL=getClass().getResource("/wsdl/hello_world_soap12.wsdl");
ServiceImpl seviceImpl=new ServiceImpl(this.getBus(),wsdlURL,serviceName,org.apache.hello_world_soap12_http.Greeter.class);
Field f=seviceImpl.getClass().getDeclaredField("portInfos");
f.setAccessible(true);
Map portInfoMap=(Map)f.get(seviceImpl);
assertEquals(portInfoMap.values().iterator().next().getBindingID(),SOAPBinding.SOAP12HTTP_BINDING);
}
Class: org.apache.cxf.jaxws.ServiceModelUtilsTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetOperationInputPartNamesRpc() throws Exception {
getService(getClass().getResource("/wsdl/hello_world_rpc_lit.wsdl"),RPCLitGreeterImpl.class,new QName("http://apache.org/hello_world_rpclit","SoapPortRPCLit"));
BindingOperationInfo operation=ServiceModelUtil.getOperation(message.getExchange(),"greetMe");
assertNotNull(operation);
List names=ServiceModelUtil.getOperationInputPartNames(operation.getOperationInfo());
assertNotNull(names);
assertEquals(1,names.size());
assertEquals("in",names.get(0));
operation=ServiceModelUtil.getOperation(message.getExchange(),"sayHi");
assertNotNull(operation);
names=ServiceModelUtil.getOperationInputPartNames(operation.getOperationInfo());
assertNotNull(names);
assertEquals(0,names.size());
operation=ServiceModelUtil.getOperation(message.getExchange(),"greetUs");
assertNotNull(operation);
names=ServiceModelUtil.getOperationInputPartNames(operation.getOperationInfo());
assertNotNull(names);
assertEquals(2,names.size());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetOperationInputPartNamesWrapped2() throws Exception {
getService(getClass().getResource("/wsdl/calculator.wsdl"),CalculatorImpl.class,new QName("http://apache.org/cxf/calculator","CalculatorPort"));
BindingOperationInfo operation=ServiceModelUtil.getOperation(message.getExchange(),"add");
assertNotNull(operation);
List names=ServiceModelUtil.getOperationInputPartNames(operation.getOperationInfo());
assertNotNull(names);
assertEquals(2,names.size());
assertEquals("arg0",names.get(0));
assertEquals("arg1",names.get(1));
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetOperationInputPartNamesBare() throws Exception {
getService(getClass().getResource("/wsdl/hello_world_xml_bare.wsdl"),org.apache.hello_world_xml_http.bare.GreeterImpl.class,new QName("http://apache.org/hello_world_xml_http/bare","XMLPort"));
BindingOperationInfo operation=ServiceModelUtil.getOperation(message.getExchange(),"greetMe");
assertNotNull(operation);
List names=ServiceModelUtil.getOperationInputPartNames(operation.getOperationInfo());
assertNotNull(names);
assertEquals(1,names.size());
assertEquals("requestType",names.get(0));
operation=ServiceModelUtil.getOperation(message.getExchange(),"sayHi");
assertNotNull(operation);
names=ServiceModelUtil.getOperationInputPartNames(operation.getOperationInfo());
assertNotNull(names);
assertEquals(0,names.size());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetOperationInputPartNamesWrapped() throws Exception {
getService(getClass().getResource("/wsdl/hello_world.wsdl"),GreeterImpl.class,new QName("http://apache.org/hello_world_soap_http","SoapPort"));
BindingOperationInfo operation=ServiceModelUtil.getOperation(message.getExchange(),"greetMe");
assertNotNull(operation);
List names=ServiceModelUtil.getOperationInputPartNames(operation.getOperationInfo());
assertNotNull(names);
assertEquals(1,names.size());
assertEquals("requestType",names.get(0));
operation=ServiceModelUtil.getOperation(message.getExchange(),"sayHi");
assertNotNull(operation);
names=ServiceModelUtil.getOperationInputPartNames(operation.getOperationInfo());
assertNotNull(names);
assertEquals(0,names.size());
}
Class: org.apache.cxf.jaxws.context.WebServiceContextImplTest BooleanVerifier InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testGetSetMessageContext(){
WebServiceContextImpl wsci=new WebServiceContextImpl();
assertNull(wsci.getMessageContext());
MessageImpl msg=new MessageImpl();
final MessageContext ctx=new WrappedMessageContext(msg);
WebServiceContextImpl.setMessageContext(ctx);
assertSame(ctx,wsci.getMessageContext());
Thread t=new Thread(){
public void run(){
WebServiceContextImpl threadLocalWSCI=new WebServiceContextImpl();
assertNull(threadLocalWSCI.getMessageContext());
MessageImpl msg1=new MessageImpl();
MessageContext threadLocalCtx=new WrappedMessageContext(msg1);
WebServiceContextImpl.setMessageContext(threadLocalCtx);
assertSame(threadLocalCtx,threadLocalWSCI.getMessageContext());
assertTrue(ctx != threadLocalWSCI.getMessageContext());
}
}
;
t.start();
try {
t.join();
}
catch ( InterruptedException e) {
e.printStackTrace();
}
}
Class: org.apache.cxf.jaxws.context.WrappedAttachmentsTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testCreateAndModify(){
Map content=new HashMap();
content.put("att-1",new DataHandler(new ByteArrayDataSource("Hello world!".getBytes(),"text/plain")));
content.put("att-2",new DataHandler(new ByteArrayDataSource("Hola mundo!".getBytes(),"text/plain")));
WrappedAttachments attachments=new WrappedAttachments(content);
Attachment att3=new AttachmentImpl("att-3",new DataHandler(new ByteArrayDataSource("Bonjour tout le monde!".getBytes(),"text/plain")));
assertEquals(2,attachments.size());
assertFalse(attachments.isEmpty());
attachments.add(att3);
assertEquals(3,attachments.size());
attachments.add(att3);
assertEquals(3,attachments.size());
attachments.remove(att3);
assertEquals(2,attachments.size());
Attachment attx=attachments.iterator().next();
attachments.remove(attx);
assertEquals(1,attachments.size());
Attachment[] atts=attachments.toArray(new Attachment[attachments.size()]);
assertEquals(1,atts.length);
assertEquals("att-1".equals(attx.getId()) ? "att-2" : "att-1",atts[0].getId());
attachments.clear();
assertTrue(attachments.isEmpty());
assertTrue(content.isEmpty());
}
Class: org.apache.cxf.jaxws.context.WrappedMessageContextTest BranchVerifier UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testPutAndGetJaxwsAttachments() throws Exception {
WrappedMessageContext context=new WrappedMessageContext(new HashMap(),null,Scope.APPLICATION);
DataHandler dh1=new DataHandler(new ByteArrayDataSource("Hello world!".getBytes(),"text/plain"));
DataHandler dh2=new DataHandler(new ByteArrayDataSource("Hola mundo!".getBytes(),"text/plain"));
DataHandler dh3=new DataHandler(new ByteArrayDataSource("Bonjour tout le monde!".getBytes(),"text/plain"));
Map jattachments=new HashMap();
context.put(MessageContext.OUTBOUND_MESSAGE_ATTACHMENTS,jattachments);
jattachments.put("attachment-1",dh1);
Set cattachments=CastUtils.cast((Set>)context.get(Message.ATTACHMENTS));
assertNotNull(cattachments);
assertEquals(1,cattachments.size());
jattachments.put("attachment-2",dh2);
assertEquals(2,cattachments.size());
AttachmentImpl ca=new AttachmentImpl("attachment-3",dh3);
ca.setHeader("X-test","true");
cattachments.add(ca);
assertEquals(3,jattachments.size());
assertEquals(3,cattachments.size());
for ( Attachment a : cattachments) {
if ("attachment-1".equals(a.getId())) {
assertEquals("Hello world!",a.getDataHandler().getContent());
}
else if ("attachment-2".equals(a.getId())) {
assertEquals("Hola mundo!",a.getDataHandler().getContent());
}
else if ("attachment-3".equals(a.getId())) {
assertEquals("Bonjour tout le monde!",a.getDataHandler().getContent());
assertEquals("true",a.getHeader("X-test"));
}
else {
fail("unknown attachment");
}
}
}
Class: org.apache.cxf.jaxws.dispatch.DispatchOpTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testResolveOperationWithSourceAndWSA() throws Exception {
ServiceImpl service=new ServiceImpl(getBus(),getClass().getResource(wsdlResource),serviceName,null,new AddressingFeature());
Dispatch disp=service.createDispatch(portName,Source.class,Service.Mode.PAYLOAD);
disp.getRequestContext().put(MessageContext.WSDL_OPERATION,operationName);
disp.getRequestContext().put(Dispatch.ENDPOINT_ADDRESS_PROPERTY,address);
d.setMessageObserver(new MessageReplayObserver(responseResource));
BindingOperationVerifier bov=new BindingOperationVerifier();
((DispatchImpl>)disp).getClient().getOutInterceptors().add(bov);
Document doc=StaxUtils.read(getResourceAsStream(requestResource));
DOMSource source=new DOMSource(doc);
Source res=disp.invoke(source);
assertNotNull(res);
BindingOperationInfo boi=bov.getBindingOperationInfo();
assertNotNull(boi);
assertEquals(operationName,boi.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testResolveOperationWithSource() throws Exception {
ServiceImpl service=new ServiceImpl(getBus(),getClass().getResource(wsdlResource),serviceName,null);
Dispatch disp=service.createDispatch(portName,Source.class,Service.Mode.PAYLOAD);
disp.getRequestContext().put(MessageContext.WSDL_OPERATION,operationName);
disp.getRequestContext().put(Dispatch.ENDPOINT_ADDRESS_PROPERTY,address);
d.setMessageObserver(new MessageReplayObserver(responseResource));
BindingOperationVerifier bov=new BindingOperationVerifier();
((DispatchImpl>)disp).getClient().getOutInterceptors().add(bov);
Document doc=StaxUtils.read(getResourceAsStream(requestResource));
DOMSource source=new DOMSource(doc);
Source res=disp.invoke(source);
assertNotNull(res);
BindingOperationInfo boi=bov.getBindingOperationInfo();
assertNotNull(boi);
assertEquals(operationName,boi.getName());
}
Class: org.apache.cxf.jaxws.dispatch.DispatchTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testFindOperationWithSource() throws Exception {
ServiceImpl service=new ServiceImpl(getBus(),getClass().getResource("/wsdl/hello_world.wsdl"),serviceName,null);
Dispatch disp=service.createDispatch(portName,Source.class,Service.Mode.MESSAGE);
disp.getRequestContext().put(Dispatch.ENDPOINT_ADDRESS_PROPERTY,address);
disp.getRequestContext().put("find.dispatch.operation",Boolean.TRUE);
d.setMessageObserver(new MessageReplayObserver("/org/apache/cxf/jaxws/sayHiResponse.xml"));
BindingOperationVerifier bov=new BindingOperationVerifier();
((DispatchImpl>)disp).getClient().getOutInterceptors().add(bov);
Document doc=StaxUtils.read(getResourceAsStream("/org/apache/cxf/jaxws/sayHi2.xml"));
DOMSource source=new DOMSource(doc);
Source res=disp.invoke(source);
assertNotNull(res);
BindingOperationInfo boi=bov.getBindingOperationInfo();
assertNotNull(boi);
assertEquals(new QName("http://apache.org/hello_world_soap_http","sayHi"),boi.getName());
}
APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testDOMSource() throws Exception {
ServiceImpl service=new ServiceImpl(getBus(),getClass().getResource("/wsdl/hello_world.wsdl"),serviceName,null);
Dispatch disp=service.createDispatch(portName,Source.class,Service.Mode.MESSAGE);
disp.getRequestContext().put(Dispatch.ENDPOINT_ADDRESS_PROPERTY,address);
d.setMessageObserver(new MessageReplayObserver("/org/apache/cxf/jaxws/sayHiResponse.xml"));
Document doc=StaxUtils.read(getResourceAsStream("/org/apache/cxf/jaxws/sayHi2.xml"));
DOMSource source=new DOMSource(doc);
Source res=disp.invoke(source);
assertNotNull(res);
}
BooleanVerifier InternalCallVerifier
@Test public void testHTTPBinding() throws Exception {
ServiceImpl service=new ServiceImpl(getBus(),null,serviceName,null);
service.addPort(portName,HTTPBinding.HTTP_BINDING,"local://foobar");
Dispatch disp=service.createDispatch(portName,Source.class,Service.Mode.MESSAGE);
assertTrue(disp.getBinding() instanceof HTTPBinding);
}
BooleanVerifier InternalCallVerifier
@Test public void testSOAPPBinding() throws Exception {
ServiceImpl service=new ServiceImpl(getBus(),null,serviceName,null);
service.addPort(portName,SOAPBinding.SOAP11HTTP_BINDING,"local://foobar");
Dispatch disp=service.createDispatch(portName,Source.class,Service.Mode.MESSAGE);
assertTrue(disp.getBinding() instanceof SOAPBinding);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testJAXB() throws Exception {
d.setMessageObserver(new MessageReplayObserver("/org/apache/cxf/jaxws/sayHiResponse.xml"));
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
assertNotNull(service);
JAXBContext jc=JAXBContext.newInstance("org.apache.hello_world_soap_http.types");
Dispatch disp=service.createDispatch(portName,jc,Service.Mode.PAYLOAD);
SayHi s=new SayHi();
Object response=disp.invoke(s);
assertNotNull(response);
assertTrue(response instanceof SayHiResponse);
}
Class: org.apache.cxf.jaxws.handler.AnnotationHandlerChainBuilderTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testFindHandlerChainAnnotationPerPortServiceBinding(){
HandlerTestImpl handlerTestImpl=new HandlerTestImpl();
AnnotationHandlerChainBuilder chainBuilder=new AnnotationHandlerChainBuilder();
QName portQName=new QName("namespacedoesntsupportyet","SoapPort1");
QName serviceQName=new QName("namespacedoesntsupportyet","SoapService1");
String bindingID="http://schemas.xmlsoap.org/wsdl/soap/http";
@SuppressWarnings("rawtypes") List handlers=chainBuilder.buildHandlerChainFromClass(handlerTestImpl.getClass(),portQName,serviceQName,bindingID);
assertNotNull(handlers);
assertEquals(5,handlers.size());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testFindHandlerChainAnnotationPerPortServiceBindingWildcard(){
HandlerTestImpl handlerTestImpl=new HandlerTestImpl();
AnnotationHandlerChainBuilder chainBuilder=new AnnotationHandlerChainBuilder();
QName portQName=new QName("http://apache.org/handler_test","SoapPortWildcard");
QName serviceQName=new QName("http://apache.org/handler_test","SoapServiceWildcard");
String bindingID="BindingUnknow";
@SuppressWarnings("rawtypes") List handlers=chainBuilder.buildHandlerChainFromClass(handlerTestImpl.getClass(),portQName,serviceQName,bindingID);
assertNotNull(handlers);
assertEquals(7,handlers.size());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testFindHandlerChainAnnotation(){
HandlerTestImpl handlerTestImpl=new HandlerTestImpl();
AnnotationHandlerChainBuilder chainBuilder=new AnnotationHandlerChainBuilder();
@SuppressWarnings("rawtypes") List handlers=chainBuilder.buildHandlerChainFromClass(handlerTestImpl.getClass(),null,null,null);
assertNotNull(handlers);
assertEquals(9,handlers.size());
assertEquals(TestLogicalHandler.class,handlers.get(0).getClass());
assertEquals(TestLogicalHandler.class,handlers.get(1).getClass());
assertEquals(TestLogicalHandler.class,handlers.get(2).getClass());
assertEquals(TestLogicalHandler.class,handlers.get(3).getClass());
assertEquals(TestLogicalHandler.class,handlers.get(4).getClass());
assertEquals(TestLogicalHandler.class,handlers.get(5).getClass());
assertEquals(TestLogicalHandler.class,handlers.get(6).getClass());
assertEquals(TestProtocolHandler.class,handlers.get(7).getClass());
assertEquals(TestProtocolHandler.class,handlers.get(8).getClass());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testFindHandlerChainAnnotationPerPortServiceBindingNegative(){
HandlerTestImpl handlerTestImpl=new HandlerTestImpl();
AnnotationHandlerChainBuilder chainBuilder=new AnnotationHandlerChainBuilder();
QName portQName=new QName("namespacedoesntsupportyet","SoapPortUnknown");
QName serviceQName=new QName("namespacedoesntsupportyet","SoapServiceUnknown");
String bindingID="BindingUnknow";
@SuppressWarnings("rawtypes") List handlers=chainBuilder.buildHandlerChainFromClass(handlerTestImpl.getClass(),portQName,serviceQName,bindingID);
assertNotNull(handlers);
assertEquals(3,handlers.size());
}
Class: org.apache.cxf.jaxws.handler.HandlerChainBuilderTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier PublicFieldVerifier HybridVerifier
@Test public void testBuilderCallsInit(){
List hc=createHandlerChainType();
hc.remove(3);
hc.remove(2);
hc.remove(1);
PortComponentHandlerType h=hc.get(0);
List params=h.getInitParam();
ParamValueType p=new ParamValueType();
CString pName=new CString();
pName.setValue("foo");
p.setParamName(pName);
XsdStringType pValue=new XsdStringType();
pValue.setValue("1");
p.setParamValue(pValue);
params.add(p);
p=new ParamValueType();
pName=new CString();
pName.setValue("bar");
p.setParamName(pName);
pValue=new XsdStringType();
pValue.setValue("2");
p.setParamValue(pValue);
params.add(p);
List chain=builder.buildHandlerChainFromConfiguration(hc);
assertEquals(1,chain.size());
TestLogicalHandler tlh=(TestLogicalHandler)chain.get(0);
assertTrue(tlh.initCalled);
Map cfg=tlh.config;
assertNotNull(tlh.config);
assertEquals(2,cfg.keySet().size());
assertEquals("1",cfg.get("foo"));
assertEquals("2",cfg.get("bar"));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBuildHandlerChainFromConfiguration(){
List hc=createHandlerChainType();
List chain=builder.buildHandlerChainFromConfiguration(hc);
assertNotNull(chain);
assertEquals(4,chain.size());
assertEquals(TestLogicalHandler.class,chain.get(0).getClass());
assertEquals(TestLogicalHandler.class,chain.get(1).getClass());
assertEquals(TestProtocolHandler.class,chain.get(2).getClass());
assertEquals(TestProtocolHandler.class,chain.get(3).getClass());
TestLogicalHandler tlh=(TestLogicalHandler)chain.get(0);
assertTrue(!tlh.initCalled);
assertNull(tlh.config);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier PublicFieldVerifier HybridVerifier
@Test public void testBuilderCallsInitWithNoInitParamValues(){
List hc=createHandlerChainType();
hc.remove(3);
hc.remove(2);
hc.remove(1);
PortComponentHandlerType h=hc.get(0);
List params=h.getInitParam();
ParamValueType p=new ParamValueType();
CString pName=new CString();
pName.setValue("foo");
p.setParamName(pName);
params.add(p);
List chain=builder.buildHandlerChainFromConfiguration(hc);
assertEquals(1,chain.size());
TestLogicalHandler tlh=(TestLogicalHandler)chain.get(0);
assertTrue(tlh.initCalled);
Map cfg=tlh.config;
assertNotNull(tlh.config);
assertEquals(1,cfg.keySet().size());
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier
@Test public void testChainSorting(){
List sortedHandlerChain=builder.sortHandlers(Arrays.asList(allHandlers));
assertSame(logicalHandlers[0],sortedHandlerChain.get(0));
assertSame(logicalHandlers[1],sortedHandlerChain.get(1));
assertSame(protocolHandlers[0],sortedHandlerChain.get(2));
assertSame(protocolHandlers[1],sortedHandlerChain.get(3));
}
Class: org.apache.cxf.jaxws.handler.HandlerChainInvokerTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testHandleMessageReturnsFalseWithNoResponseExpected(){
assertFalse(invoker.faultRaised());
logicalHandlers[0].setHandleMessageRet(true);
logicalHandlers[1].setHandleMessageRet(true);
logicalHandlers[2].setHandleMessageRet(false);
logicalHandlers[3].setHandleMessageRet(true);
invoker.setResponseExpected(false);
boolean continueProcessing=true;
continueProcessing=invoker.invokeLogicalHandlers(false,lmc);
assertFalse(continueProcessing);
assertEquals(1,logicalHandlers[0].getHandleMessageCount());
assertEquals(1,logicalHandlers[1].getHandleMessageCount());
assertEquals(1,logicalHandlers[2].getHandleMessageCount());
assertEquals(0,logicalHandlers[3].getHandleMessageCount());
assertTrue(logicalHandlers[0].getInvokeOrderOfHandleMessage() < logicalHandlers[1].getInvokeOrderOfHandleMessage());
assertTrue(logicalHandlers[1].getInvokeOrderOfHandleMessage() < logicalHandlers[2].getInvokeOrderOfHandleMessage());
assertEquals(1,logicalHandlers[0].getCloseCount());
assertEquals(1,logicalHandlers[1].getCloseCount());
assertEquals(1,logicalHandlers[2].getCloseCount());
assertEquals(0,logicalHandlers[3].getCloseCount());
assertEquals(0,logicalHandlers[0].getHandleFaultCount());
assertEquals(0,logicalHandlers[1].getHandleFaultCount());
assertEquals(0,logicalHandlers[2].getHandleFaultCount());
assertEquals(0,logicalHandlers[3].getHandleFaultCount());
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testMEPComplete(){
invoker.invokeLogicalHandlers(false,lmc);
invoker.invokeProtocolHandlers(false,pmc);
assertEquals(8,invoker.getInvokedHandlers().size());
invoker.mepComplete(message);
assertTrue("close not invoked on logicalHandlers",logicalHandlers[0].isCloseInvoked());
assertTrue("close not invoked on logicalHandlers",logicalHandlers[1].isCloseInvoked());
assertTrue("close not invoked on protocolHandlers",protocolHandlers[0].isCloseInvoked());
assertTrue("close not invoked on protocolHandlers",protocolHandlers[1].isCloseInvoked());
assertTrue("incorrect invocation order of close",protocolHandlers[1].getInvokeOrderOfClose() < protocolHandlers[0].getInvokeOrderOfClose());
assertTrue("incorrect invocation order of close",protocolHandlers[0].getInvokeOrderOfClose() < logicalHandlers[1].getInvokeOrderOfClose());
assertTrue("incorrect invocation order of close",logicalHandlers[1].getInvokeOrderOfClose() < logicalHandlers[0].getInvokeOrderOfClose());
}
UtilityVerifier BooleanVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testHandleMessageThrowsProtocolExceptionWithResponseExpected(){
assertFalse(invoker.faultRaised());
ProtocolException pe=new ProtocolException("banzai");
logicalHandlers[2].setException(pe);
invoker.setRequestor(true);
try {
invoker.setLogicalMessageContext(lmc);
invoker.invokeLogicalHandlers(false,lmc);
fail("did not get expected exception");
}
catch ( ProtocolException e) {
assertEquals("banzai",e.getMessage());
}
assertTrue(invoker.faultRaised());
assertSame(pe,invoker.getFault());
assertFalse((Boolean)lmc.get(LogicalMessageContext.MESSAGE_OUTBOUND_PROPERTY));
assertEquals(1,logicalHandlers[0].getHandleMessageCount());
assertEquals(1,logicalHandlers[1].getHandleMessageCount());
assertEquals(1,logicalHandlers[2].getHandleMessageCount());
assertEquals(0,logicalHandlers[3].getHandleMessageCount());
assertTrue(logicalHandlers[1].getInvokeOrderOfHandleMessage() < logicalHandlers[2].getInvokeOrderOfHandleMessage());
assertEquals(1,logicalHandlers[0].getHandleFaultCount());
assertEquals(1,logicalHandlers[1].getHandleFaultCount());
assertEquals(0,logicalHandlers[2].getHandleFaultCount());
assertEquals(0,logicalHandlers[2].getHandleFaultCount());
assertTrue(logicalHandlers[1].getInvokeOrderOfHandleFault() < logicalHandlers[0].getInvokeOrderOfHandleFault());
assertEquals(1,logicalHandlers[0].getCloseCount());
assertEquals(1,logicalHandlers[1].getCloseCount());
assertEquals(1,logicalHandlers[2].getCloseCount());
assertEquals(0,logicalHandlers[3].getCloseCount());
}
UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testHandleFaultThrowsRuntimeException(){
ProtocolException pe=new ProtocolException("banzai");
RuntimeException re=new RuntimeException("banzai");
logicalHandlers[2].setException(pe);
logicalHandlers[1].setFaultException(re);
invoker.setRequestor(true);
boolean continueProcessing=false;
try {
continueProcessing=invoker.invokeLogicalHandlers(false,lmc);
fail("did not get expected exception");
}
catch ( RuntimeException e) {
assertEquals("banzai",e.getMessage());
}
assertFalse(continueProcessing);
assertTrue(invoker.isClosed());
assertEquals(1,logicalHandlers[0].getHandleMessageCount());
assertEquals(1,logicalHandlers[1].getHandleMessageCount());
assertEquals(1,logicalHandlers[2].getHandleMessageCount());
assertEquals(0,logicalHandlers[3].getHandleMessageCount());
assertEquals(0,logicalHandlers[0].getHandleFaultCount());
assertEquals(1,logicalHandlers[1].getHandleFaultCount());
assertEquals(0,logicalHandlers[2].getHandleFaultCount());
assertEquals(1,logicalHandlers[0].getCloseCount());
assertEquals(1,logicalHandlers[1].getCloseCount());
assertEquals(1,logicalHandlers[2].getCloseCount());
assertEquals(0,logicalHandlers[3].getCloseCount());
assertTrue(logicalHandlers[2].getInvokeOrderOfClose() < logicalHandlers[1].getInvokeOrderOfClose());
assertTrue(logicalHandlers[1].getInvokeOrderOfClose() < logicalHandlers[0].getInvokeOrderOfClose());
}
UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testHandleFaultReturnsTrue(){
ProtocolException pe=new ProtocolException("banzai");
logicalHandlers[2].setException(pe);
invoker.setRequestor(true);
logicalHandlers[0].setHandleFaultRet(true);
logicalHandlers[1].setHandleFaultRet(true);
logicalHandlers[2].setHandleFaultRet(true);
logicalHandlers[3].setHandleFaultRet(true);
boolean continueProcessing=false;
try {
continueProcessing=invoker.invokeLogicalHandlers(false,lmc);
fail("did not get expected exception");
}
catch ( RuntimeException e) {
assertEquals("banzai",e.getMessage());
}
assertFalse(continueProcessing);
assertEquals(1,logicalHandlers[0].getHandleMessageCount());
assertEquals(1,logicalHandlers[1].getHandleMessageCount());
assertEquals(1,logicalHandlers[2].getHandleMessageCount());
assertEquals(0,logicalHandlers[3].getHandleMessageCount());
assertEquals(1,logicalHandlers[0].getHandleFaultCount());
assertEquals(1,logicalHandlers[1].getHandleFaultCount());
assertEquals(0,logicalHandlers[2].getHandleFaultCount());
assertEquals(0,logicalHandlers[3].getHandleFaultCount());
assertTrue(logicalHandlers[1].getInvokeOrderOfHandleFault() < logicalHandlers[0].getInvokeOrderOfHandleFault());
assertEquals(1,logicalHandlers[0].getCloseCount());
assertEquals(1,logicalHandlers[1].getCloseCount());
assertEquals(1,logicalHandlers[2].getCloseCount());
assertEquals(0,logicalHandlers[3].getCloseCount());
}
UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testHandleFaultReturnsFalseOutbound(){
ProtocolException pe=new ProtocolException("banzai");
protocolHandlers[2].setException(pe);
protocolHandlers[0].setHandleFaultRet(false);
invoker.setRequestor(true);
assertTrue(invoker.isOutbound());
boolean continueProcessing=true;
invoker.setLogicalMessageContext(lmc);
continueProcessing=invoker.invokeLogicalHandlers(false,lmc);
assertTrue(continueProcessing);
try {
invoker.setProtocolMessageContext(pmc);
continueProcessing=invoker.invokeProtocolHandlers(false,pmc);
fail("did not get expected exception");
}
catch ( ProtocolException e) {
assertEquals("banzai",e.getMessage());
}
assertFalse((Boolean)pmc.get(SOAPMessageContext.MESSAGE_OUTBOUND_PROPERTY));
assertFalse((Boolean)lmc.get(LogicalMessageContext.MESSAGE_OUTBOUND_PROPERTY));
assertTrue(invoker.isInbound());
assertEquals(1,logicalHandlers[0].getHandleMessageCount());
assertEquals(1,logicalHandlers[1].getHandleMessageCount());
assertEquals(1,logicalHandlers[2].getHandleMessageCount());
assertEquals(1,logicalHandlers[3].getHandleMessageCount());
assertEquals(1,protocolHandlers[0].getHandleMessageCount());
assertEquals(1,protocolHandlers[1].getHandleMessageCount());
assertEquals(1,protocolHandlers[2].getHandleMessageCount());
assertEquals(0,protocolHandlers[3].getHandleMessageCount());
assertTrue(logicalHandlers[3].getInvokeOrderOfHandleMessage() < protocolHandlers[0].getInvokeOrderOfHandleMessage());
assertTrue(protocolHandlers[1].getInvokeOrderOfHandleMessage() < protocolHandlers[2].getInvokeOrderOfHandleMessage());
assertEquals(1,logicalHandlers[0].getCloseCount());
assertEquals(1,logicalHandlers[1].getCloseCount());
assertEquals(1,logicalHandlers[2].getCloseCount());
assertEquals(1,logicalHandlers[3].getCloseCount());
assertEquals(1,protocolHandlers[0].getCloseCount());
assertEquals(1,protocolHandlers[1].getCloseCount());
assertEquals(1,protocolHandlers[2].getCloseCount());
assertEquals(0,protocolHandlers[3].getCloseCount());
assertTrue(protocolHandlers[2].getInvokeOrderOfClose() < protocolHandlers[1].getInvokeOrderOfClose());
assertTrue(protocolHandlers[0].getInvokeOrderOfClose() < logicalHandlers[3].getInvokeOrderOfClose());
assertEquals(0,logicalHandlers[0].getHandleFaultCount());
assertEquals(0,logicalHandlers[1].getHandleFaultCount());
assertEquals(0,logicalHandlers[2].getHandleFaultCount());
assertEquals(0,logicalHandlers[3].getHandleFaultCount());
assertEquals(1,protocolHandlers[0].getHandleFaultCount());
assertEquals(1,protocolHandlers[1].getHandleFaultCount());
assertEquals(0,protocolHandlers[2].getHandleFaultCount());
assertEquals(0,protocolHandlers[3].getHandleFaultCount());
assertTrue(protocolHandlers[2].getInvokeOrderOfHandleFault() < protocolHandlers[1].getInvokeOrderOfHandleFault());
}
APIUtilityVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testHandleMessageThrowsProtocolExceptionOutbound(){
message=new SoapMessage(message);
lmc=new LogicalMessageContextImpl(message);
pmc=new WrappedMessageContext(message);
ProtocolException pe=new ProtocolException("banzai");
protocolHandlers[2].setException(pe);
invoker.setRequestor(true);
assertTrue(invoker.isOutbound());
boolean continueProcessing=true;
invoker.setLogicalMessageContext(lmc);
continueProcessing=invoker.invokeLogicalHandlers(false,lmc);
assertTrue(continueProcessing);
try {
pmc=new SOAPMessageContextImpl(message);
MessageFactory factory=MessageFactory.newInstance();
SOAPMessage soapMessage=factory.createMessage();
((SOAPMessageContext)pmc).setMessage(soapMessage);
}
catch ( SOAPException e) {
}
try {
invoker.setProtocolMessageContext(pmc);
continueProcessing=invoker.invokeProtocolHandlers(false,pmc);
fail("did not get expected exception");
}
catch ( ProtocolException e) {
assertEquals("banzai",e.getMessage());
}
assertFalse((Boolean)pmc.get(SOAPMessageContext.MESSAGE_OUTBOUND_PROPERTY));
assertFalse((Boolean)lmc.get(LogicalMessageContext.MESSAGE_OUTBOUND_PROPERTY));
assertTrue(invoker.isInbound());
Source responseMessage=lmc.getMessage().getPayload();
assertTrue(getSourceAsString(responseMessage).indexOf("banzai") > -1);
assertEquals(1,logicalHandlers[0].getHandleMessageCount());
assertEquals(1,logicalHandlers[1].getHandleMessageCount());
assertEquals(1,logicalHandlers[2].getHandleMessageCount());
assertEquals(1,logicalHandlers[3].getHandleMessageCount());
assertEquals(1,protocolHandlers[0].getHandleMessageCount());
assertEquals(1,protocolHandlers[1].getHandleMessageCount());
assertEquals(1,protocolHandlers[2].getHandleMessageCount());
assertEquals(0,protocolHandlers[3].getHandleMessageCount());
assertTrue(logicalHandlers[3].getInvokeOrderOfHandleMessage() < protocolHandlers[0].getInvokeOrderOfHandleMessage());
assertTrue(protocolHandlers[1].getInvokeOrderOfHandleMessage() < protocolHandlers[2].getInvokeOrderOfHandleMessage());
assertEquals(1,logicalHandlers[0].getCloseCount());
assertEquals(1,logicalHandlers[1].getCloseCount());
assertEquals(1,logicalHandlers[2].getCloseCount());
assertEquals(1,logicalHandlers[3].getCloseCount());
assertEquals(1,protocolHandlers[0].getCloseCount());
assertEquals(1,protocolHandlers[1].getCloseCount());
assertEquals(1,protocolHandlers[2].getCloseCount());
assertEquals(0,protocolHandlers[3].getCloseCount());
assertTrue(protocolHandlers[2].getInvokeOrderOfClose() < protocolHandlers[1].getInvokeOrderOfClose());
assertTrue(protocolHandlers[0].getInvokeOrderOfClose() < logicalHandlers[3].getInvokeOrderOfClose());
assertEquals(1,logicalHandlers[0].getHandleFaultCount());
assertEquals(1,logicalHandlers[1].getHandleFaultCount());
assertEquals(1,logicalHandlers[2].getHandleFaultCount());
assertEquals(1,logicalHandlers[3].getHandleFaultCount());
assertEquals(1,protocolHandlers[0].getHandleFaultCount());
assertEquals(1,protocolHandlers[1].getHandleFaultCount());
assertEquals(0,protocolHandlers[2].getHandleFaultCount());
assertEquals(0,protocolHandlers[3].getHandleFaultCount());
assertTrue(protocolHandlers[0].getInvokeOrderOfHandleFault() < logicalHandlers[3].getInvokeOrderOfHandleFault());
assertTrue(protocolHandlers[2].getInvokeOrderOfHandleFault() < protocolHandlers[1].getInvokeOrderOfHandleFault());
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testLogicalHandlerInboundProcessingStoppedResponseExpected(){
assertEquals(0,logicalHandlers[0].getHandleMessageCount());
assertEquals(0,logicalHandlers[1].getHandleMessageCount());
invoker.setInbound();
logicalHandlers[1].setHandleMessageRet(false);
boolean ret=invoker.invokeLogicalHandlers(false,lmc);
assertFalse(invoker.isClosed());
assertEquals(false,ret);
assertEquals(0,logicalHandlers[0].getHandleMessageCount());
assertEquals(1,logicalHandlers[1].getHandleMessageCount());
assertTrue(invoker.isOutbound());
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testHandlerPartitioning(){
assertEquals(HANDLER_COUNT,invoker.getLogicalHandlers().size());
for ( Handler> h : invoker.getLogicalHandlers()) {
assertTrue(h instanceof LogicalHandler);
}
assertEquals(HANDLER_COUNT,invoker.getProtocolHandlers().size());
for ( Handler> h : invoker.getProtocolHandlers()) {
assertTrue(!(h instanceof LogicalHandler));
}
}
UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testHandleFaultThrowsProtocolException(){
ProtocolException pe=new ProtocolException("banzai");
ProtocolException pe2=new ProtocolException("banzai2");
logicalHandlers[2].setException(pe);
logicalHandlers[1].setFaultException(pe2);
invoker.setRequestor(true);
boolean continueProcessing=false;
try {
continueProcessing=invoker.invokeLogicalHandlers(false,lmc);
fail("did not get expected exception");
}
catch ( ProtocolException e) {
assertEquals("banzai2",e.getMessage());
}
assertFalse(continueProcessing);
assertTrue(invoker.isClosed());
assertEquals(1,logicalHandlers[0].getHandleMessageCount());
assertEquals(1,logicalHandlers[1].getHandleMessageCount());
assertEquals(1,logicalHandlers[2].getHandleMessageCount());
assertEquals(0,logicalHandlers[3].getHandleMessageCount());
assertTrue(logicalHandlers[1].getInvokeOrderOfHandleMessage() < logicalHandlers[2].getInvokeOrderOfHandleMessage());
assertEquals(0,logicalHandlers[0].getHandleFaultCount());
assertEquals(1,logicalHandlers[1].getHandleFaultCount());
assertEquals(0,logicalHandlers[2].getHandleFaultCount());
assertEquals(1,logicalHandlers[0].getCloseCount());
assertEquals(1,logicalHandlers[1].getCloseCount());
assertEquals(1,logicalHandlers[2].getCloseCount());
assertEquals(0,logicalHandlers[3].getCloseCount());
assertTrue(logicalHandlers[2].getInvokeOrderOfClose() < logicalHandlers[1].getInvokeOrderOfClose());
assertTrue(logicalHandlers[1].getInvokeOrderOfClose() < logicalHandlers[0].getInvokeOrderOfClose());
}
UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testHandleMessageThrowsRuntimeExceptionWithResponseExpected(){
assertFalse(invoker.faultRaised());
RuntimeException re=new RuntimeException("banzai");
logicalHandlers[1].setException(re);
invoker.setRequestor(true);
try {
invoker.invokeLogicalHandlers(false,lmc);
fail("did not get expected exception");
}
catch ( RuntimeException e) {
assertEquals("banzai",e.getMessage());
}
assertTrue(invoker.isClosed());
assertEquals(1,logicalHandlers[0].getHandleMessageCount());
assertEquals(1,logicalHandlers[1].getHandleMessageCount());
assertEquals(0,logicalHandlers[2].getHandleMessageCount());
assertEquals(0,logicalHandlers[3].getHandleMessageCount());
assertTrue(logicalHandlers[0].getInvokeOrderOfHandleMessage() < logicalHandlers[1].getInvokeOrderOfHandleMessage());
assertEquals(0,logicalHandlers[0].getHandleFaultCount());
assertEquals(0,logicalHandlers[1].getHandleFaultCount());
assertEquals(0,logicalHandlers[2].getHandleFaultCount());
assertEquals(0,logicalHandlers[3].getHandleFaultCount());
assertEquals(1,logicalHandlers[0].getCloseCount());
assertEquals(1,logicalHandlers[1].getCloseCount());
assertEquals(0,logicalHandlers[2].getCloseCount());
assertEquals(0,logicalHandlers[3].getCloseCount());
}
BooleanVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testHandleMessageThrowsProtocolExceptionWithNoResponseExpected(){
assertFalse(invoker.faultRaised());
ProtocolException pe=new ProtocolException("banzai");
logicalHandlers[2].setException(pe);
invoker.setResponseExpected(false);
invoker.setRequestor(true);
try {
invoker.invokeLogicalHandlers(false,lmc);
}
catch ( ProtocolException e) {
assertEquals("banzai",e.getMessage());
}
assertTrue(invoker.faultRaised());
assertSame(pe,invoker.getFault());
assertEquals(1,logicalHandlers[0].getHandleMessageCount());
assertEquals(1,logicalHandlers[1].getHandleMessageCount());
assertEquals(1,logicalHandlers[2].getHandleMessageCount());
assertEquals(0,logicalHandlers[3].getHandleMessageCount());
assertTrue(logicalHandlers[1].getInvokeOrderOfHandleMessage() < logicalHandlers[2].getInvokeOrderOfHandleMessage());
assertEquals(0,logicalHandlers[0].getHandleFaultCount());
assertEquals(0,logicalHandlers[1].getHandleFaultCount());
assertEquals(0,logicalHandlers[2].getHandleFaultCount());
assertEquals(0,logicalHandlers[3].getHandleFaultCount());
assertEquals(1,logicalHandlers[0].getCloseCount());
assertEquals(1,logicalHandlers[1].getCloseCount());
assertEquals(1,logicalHandlers[2].getCloseCount());
assertEquals(0,logicalHandlers[3].getCloseCount());
assertTrue(logicalHandlers[1].getInvokeOrderOfClose() < logicalHandlers[0].getInvokeOrderOfClose());
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testInvokedAlreadyInvokedMixed(){
logicalHandlers[1].setHandleMessageRet(false);
invoker.setInbound();
invoker.invokeProtocolHandlers(true,pmc);
invoker.invokeLogicalHandlers(true,lmc);
assertEquals(7,invoker.getInvokedHandlers().size());
assertTrue(invoker.getInvokedHandlers().contains(protocolHandlers[0]));
assertTrue(invoker.getInvokedHandlers().contains(protocolHandlers[1]));
assertEquals(0,logicalHandlers[0].getHandleMessageCount());
assertEquals(1,logicalHandlers[1].getHandleMessageCount());
logicalHandlers[1].setHandleMessageRet(true);
invoker.invokeLogicalHandlers(true,lmc);
invoker.invokeProtocolHandlers(true,pmc);
assertEquals(2,protocolHandlers[0].getHandleMessageCount());
assertEquals(2,protocolHandlers[1].getHandleMessageCount());
assertEquals(1,logicalHandlers[1].getHandleMessageCount());
assertEquals(0,logicalHandlers[0].getHandleMessageCount());
assertEquals(2,protocolHandlers[0].getHandleMessageCount());
assertEquals(2,protocolHandlers[1].getHandleMessageCount());
}
UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testHandleFaultReturnsFalse(){
ProtocolException pe=new ProtocolException("banzai");
logicalHandlers[3].setException(pe);
invoker.setRequestor(true);
logicalHandlers[0].setHandleFaultRet(true);
logicalHandlers[1].setHandleFaultRet(true);
logicalHandlers[2].setHandleFaultRet(false);
logicalHandlers[3].setHandleFaultRet(true);
boolean continueProcessing=false;
try {
continueProcessing=invoker.invokeLogicalHandlers(false,lmc);
fail("did not get expected exception");
}
catch ( RuntimeException e) {
assertEquals("banzai",e.getMessage());
}
assertFalse(continueProcessing);
assertEquals(1,logicalHandlers[0].getHandleMessageCount());
assertEquals(1,logicalHandlers[1].getHandleMessageCount());
assertEquals(1,logicalHandlers[2].getHandleMessageCount());
assertEquals(1,logicalHandlers[3].getHandleMessageCount());
assertEquals(0,logicalHandlers[0].getHandleFaultCount());
assertEquals(0,logicalHandlers[1].getHandleFaultCount());
assertEquals(1,logicalHandlers[2].getHandleFaultCount());
assertEquals(0,logicalHandlers[3].getHandleFaultCount());
assertEquals(1,logicalHandlers[0].getCloseCount());
assertEquals(1,logicalHandlers[1].getCloseCount());
assertEquals(1,logicalHandlers[2].getCloseCount());
assertEquals(1,logicalHandlers[3].getCloseCount());
assertTrue(logicalHandlers[3].getInvokeOrderOfClose() < logicalHandlers[2].getInvokeOrderOfClose());
assertTrue(logicalHandlers[2].getInvokeOrderOfClose() < logicalHandlers[1].getInvokeOrderOfClose());
assertTrue(logicalHandlers[1].getInvokeOrderOfClose() < logicalHandlers[0].getInvokeOrderOfClose());
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testHandleMessageReturnsFalseWithResponseExpected(){
assertFalse(invoker.faultRaised());
logicalHandlers[0].setHandleMessageRet(true);
logicalHandlers[1].setHandleMessageRet(true);
logicalHandlers[2].setHandleMessageRet(false);
logicalHandlers[3].setHandleMessageRet(true);
invoker.setResponseExpected(true);
boolean continueProcessing=true;
invoker.setLogicalMessageContext(lmc);
continueProcessing=invoker.invokeLogicalHandlers(false,lmc);
assertFalse(continueProcessing);
assertFalse((Boolean)lmc.get(LogicalMessageContext.MESSAGE_OUTBOUND_PROPERTY));
assertEquals(1,logicalHandlers[0].getHandleMessageCount());
assertEquals(1,logicalHandlers[1].getHandleMessageCount());
assertEquals(1,logicalHandlers[2].getHandleMessageCount());
assertEquals(0,logicalHandlers[3].getHandleMessageCount());
logicalHandlers[2].setHandleMessageRet(true);
invoker.invokeLogicalHandlers(false,lmc);
assertEquals(2,logicalHandlers[0].getHandleMessageCount());
assertEquals(2,logicalHandlers[1].getHandleMessageCount());
assertEquals(1,logicalHandlers[2].getHandleMessageCount());
assertEquals(0,logicalHandlers[3].getHandleMessageCount());
assertTrue(logicalHandlers[3].getInvokeOrderOfHandleMessage() < logicalHandlers[2].getInvokeOrderOfHandleMessage());
assertTrue(logicalHandlers[2].getInvokeOrderOfHandleMessage() < logicalHandlers[1].getInvokeOrderOfHandleMessage());
assertTrue(logicalHandlers[1].getInvokeOrderOfHandleMessage() < logicalHandlers[0].getInvokeOrderOfHandleMessage());
assertEquals(0,logicalHandlers[0].getCloseCount());
assertEquals(0,logicalHandlers[1].getCloseCount());
assertEquals(0,logicalHandlers[2].getCloseCount());
assertEquals(0,logicalHandlers[0].getHandleFaultCount());
assertEquals(0,logicalHandlers[1].getHandleFaultCount());
assertEquals(0,logicalHandlers[2].getHandleFaultCount());
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testHandleMessageReturnsFalseOutbound(){
protocolHandlers[2].setHandleMessageRet(false);
assertTrue(invoker.isOutbound());
boolean continueProcessing=true;
invoker.setLogicalMessageContext(lmc);
continueProcessing=invoker.invokeLogicalHandlers(false,lmc);
invoker.setProtocolMessageContext(pmc);
continueProcessing=invoker.invokeProtocolHandlers(false,pmc);
assertFalse((Boolean)pmc.get(SOAPMessageContext.MESSAGE_OUTBOUND_PROPERTY));
assertFalse((Boolean)lmc.get(LogicalMessageContext.MESSAGE_OUTBOUND_PROPERTY));
assertTrue(invoker.isInbound());
assertFalse(continueProcessing);
protocolHandlers[2].setHandleMessageRet(true);
invoker.setProtocolMessageContext(pmc);
continueProcessing=invoker.invokeProtocolHandlers(false,pmc);
invoker.setLogicalMessageContext(lmc);
continueProcessing=invoker.invokeLogicalHandlers(false,lmc);
assertEquals(2,logicalHandlers[0].getHandleMessageCount());
assertEquals(2,logicalHandlers[1].getHandleMessageCount());
assertEquals(2,logicalHandlers[2].getHandleMessageCount());
assertEquals(2,logicalHandlers[3].getHandleMessageCount());
assertEquals(2,protocolHandlers[0].getHandleMessageCount());
assertEquals(2,protocolHandlers[1].getHandleMessageCount());
assertEquals(1,protocolHandlers[2].getHandleMessageCount());
assertEquals(0,protocolHandlers[3].getHandleMessageCount());
assertTrue(logicalHandlers[3].getInvokeOrderOfHandleMessage() < logicalHandlers[2].getInvokeOrderOfHandleMessage());
assertTrue(logicalHandlers[2].getInvokeOrderOfHandleMessage() < logicalHandlers[1].getInvokeOrderOfHandleMessage());
assertTrue(logicalHandlers[1].getInvokeOrderOfHandleMessage() < logicalHandlers[0].getInvokeOrderOfHandleMessage());
assertTrue(protocolHandlers[0].getInvokeOrderOfHandleMessage() < logicalHandlers[3].getInvokeOrderOfHandleMessage());
assertTrue(protocolHandlers[2].getInvokeOrderOfHandleMessage() < protocolHandlers[1].getInvokeOrderOfHandleMessage());
assertEquals(0,logicalHandlers[0].getCloseCount());
assertEquals(0,logicalHandlers[1].getCloseCount());
assertEquals(0,logicalHandlers[2].getCloseCount());
assertEquals(0,logicalHandlers[0].getHandleFaultCount());
assertEquals(0,logicalHandlers[1].getHandleFaultCount());
assertEquals(0,logicalHandlers[2].getHandleFaultCount());
assertEquals(0,protocolHandlers[0].getCloseCount());
assertEquals(0,protocolHandlers[1].getCloseCount());
assertEquals(0,protocolHandlers[2].getCloseCount());
assertEquals(0,protocolHandlers[0].getHandleFaultCount());
assertEquals(0,protocolHandlers[1].getHandleFaultCount());
assertEquals(0,protocolHandlers[2].getHandleFaultCount());
}
BooleanVerifier InternalCallVerifier
@SuppressWarnings("rawtypes") @Test public void testInvokeEmptyHandlerChain(){
invoker=new HandlerChainInvoker(new ArrayList());
assertTrue(invoker.invokeLogicalHandlers(false,lmc));
assertTrue(invoker.invokeProtocolHandlers(false,pmc));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testInvokeHandlersInbound(){
invoker.setInbound();
assertTrue(invoker.isInbound());
checkProtocolHandlersInvoked(false);
assertEquals(4,invoker.getInvokedHandlers().size());
assertTrue(invoker.isInbound());
checkLogicalHandlersInvoked(false,true);
assertEquals(8,invoker.getInvokedHandlers().size());
assertTrue(invoker.isInbound());
assertFalse(invoker.isClosed());
assertTrue(logicalHandlers[0].getInvokeOrderOfHandleMessage() > logicalHandlers[1].getInvokeOrderOfHandleMessage());
assertTrue(logicalHandlers[1].getInvokeOrderOfHandleMessage() > protocolHandlers[0].getInvokeOrderOfHandleMessage());
assertTrue(protocolHandlers[0].getInvokeOrderOfHandleMessage() > protocolHandlers[1].getInvokeOrderOfHandleMessage());
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testHandleMessageReturnsTrue(){
assertFalse(invoker.faultRaised());
logicalHandlers[0].setHandleMessageRet(true);
logicalHandlers[1].setHandleMessageRet(true);
logicalHandlers[2].setHandleMessageRet(true);
logicalHandlers[3].setHandleMessageRet(true);
boolean continueProcessing=true;
continueProcessing=invoker.invokeLogicalHandlers(false,lmc);
assertTrue(continueProcessing);
assertEquals(1,logicalHandlers[0].getHandleMessageCount());
assertEquals(1,logicalHandlers[1].getHandleMessageCount());
assertEquals(1,logicalHandlers[2].getHandleMessageCount());
assertEquals(1,logicalHandlers[3].getHandleMessageCount());
assertTrue(logicalHandlers[0].getInvokeOrderOfHandleMessage() < logicalHandlers[1].getInvokeOrderOfHandleMessage());
assertTrue(logicalHandlers[1].getInvokeOrderOfHandleMessage() < logicalHandlers[2].getInvokeOrderOfHandleMessage());
assertTrue(logicalHandlers[2].getInvokeOrderOfHandleMessage() < logicalHandlers[3].getInvokeOrderOfHandleMessage());
assertEquals(0,logicalHandlers[0].getCloseCount());
assertEquals(0,logicalHandlers[1].getCloseCount());
assertEquals(0,logicalHandlers[2].getCloseCount());
assertEquals(0,logicalHandlers[3].getCloseCount());
assertEquals(0,logicalHandlers[0].getHandleFaultCount());
assertEquals(0,logicalHandlers[1].getHandleFaultCount());
assertEquals(0,logicalHandlers[2].getHandleFaultCount());
assertEquals(0,logicalHandlers[3].getHandleFaultCount());
}
BooleanVerifier InternalCallVerifier
@Test public void testFaultRaised(){
assertFalse(invoker.faultRaised());
invoker.setFault(new ProtocolException("test exception"));
assertTrue(invoker.faultRaised());
invoker.setFault(null);
assertFalse(invoker.faultRaised());
invoker.setFault(true);
assertTrue(invoker.faultRaised());
invoker.setFault(false);
invoker.setFault(null);
assertFalse(invoker.faultRaised());
invoker.setFault(true);
invoker.setFault(new ProtocolException("test exception"));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testLogicalHandlerReturnFalseOutboundResponseExpected(){
assertEquals(0,logicalHandlers[0].getHandleMessageCount());
assertEquals(0,logicalHandlers[1].getHandleMessageCount());
assertEquals(0,logicalHandlers[2].getHandleMessageCount());
assertTrue(invoker.isOutbound());
logicalHandlers[1].setHandleMessageRet(false);
boolean ret=invoker.invokeLogicalHandlers(false,lmc);
assertEquals(false,ret);
assertFalse(invoker.isClosed());
assertEquals(1,logicalHandlers[0].getHandleMessageCount());
assertEquals(1,logicalHandlers[1].getHandleMessageCount());
assertEquals(0,logicalHandlers[2].getHandleMessageCount());
assertTrue(invoker.isInbound());
logicalHandlers[1].setHandleMessageRet(true);
ret=invoker.invokeLogicalHandlers(false,lmc);
assertTrue(ret);
assertFalse(invoker.isClosed());
assertEquals(2,logicalHandlers[0].getHandleMessageCount());
assertEquals(1,logicalHandlers[1].getHandleMessageCount());
assertEquals(0,logicalHandlers[2].getHandleMessageCount());
assertTrue(invoker.isInbound());
}
Class: org.apache.cxf.jaxws.handler.InitParamResourceResolverTest InternalCallVerifier EqualityVerifier
@Test public void testResolveString(){
String ret=resolver.resolve(STRING_PARAM,String.class);
assertEquals("incorrect string value returned",STRING_VALUE,ret);
}
Class: org.apache.cxf.jaxws.handler.LogicalMessageImplTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testGetPayloadOfJAXB() throws Exception {
JAXBContext ctx=JAXBContext.newInstance(ObjectFactory.class);
Message message=new MessageImpl();
Exchange e=new ExchangeImpl();
message.setExchange(e);
LogicalMessageContextImpl lmci=new LogicalMessageContextImpl(message);
JAXBElement el=new ObjectFactory().createAddNumbers(req);
LogicalMessageImpl lmi=new LogicalMessageImpl(lmci);
lmi.setPayload(el,ctx);
Object obj=lmi.getPayload(ctx);
assertTrue(obj instanceof JAXBElement);
JAXBElement> el2=(JAXBElement>)obj;
assertTrue(el2.getValue() instanceof AddNumbers);
AddNumbers resp=(AddNumbers)el2.getValue();
assertEquals(req.getArg0(),resp.getArg0());
assertEquals(req.getArg1(),resp.getArg1());
}
Class: org.apache.cxf.jaxws.handler.soap.SOAPHandlerInterceptorTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testChangeSOAPHeaderInBound() throws Exception {
@SuppressWarnings("rawtypes") List list=new ArrayList();
list.add(new SOAPHandler(){
public boolean handleMessage( SOAPMessageContext smc){
try {
Boolean outboundProperty=(Boolean)smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (!outboundProperty.booleanValue()) {
SOAPMessage message=smc.getMessage();
SOAPHeader soapHeader=message.getSOAPHeader();
Element headerElementNew=(Element)soapHeader.getFirstChild();
SoapVersion soapVersion=Soap11.getInstance();
Attr attr=headerElementNew.getOwnerDocument().createAttributeNS(soapVersion.getNamespace(),"SOAP-ENV:mustUnderstand");
attr.setValue("false");
headerElementNew.setAttributeNodeNS(attr);
}
}
catch ( Exception e) {
throw new Fault(e);
}
return true;
}
public boolean handleFault( SOAPMessageContext smc){
return true;
}
public Set getHeaders(){
return null;
}
public void close( MessageContext messageContext){
}
}
);
HandlerChainInvoker invoker=new HandlerChainInvoker(list);
IMocksControl control=createNiceControl();
Binding binding=control.createMock(Binding.class);
expect(binding.getHandlerChain()).andReturn(list).anyTimes();
Exchange exchange=control.createMock(Exchange.class);
expect(exchange.get(HandlerChainInvoker.class)).andReturn(invoker).anyTimes();
expect(exchange.getOutMessage()).andReturn(null);
SoapMessage message=new SoapMessage(new MessageImpl());
message.setExchange(exchange);
XMLStreamReader reader=preparemXMLStreamReader("resources/greetMeRpcLitReq.xml");
message.setContent(XMLStreamReader.class,reader);
Object[] headerInfo=prepareSOAPHeader();
message.setContent(Node.class,headerInfo[0]);
Node node=((Element)headerInfo[1]).getFirstChild();
message.getHeaders().add(new Header(new QName(node.getNamespaceURI(),node.getLocalName()),node));
control.replay();
SOAPHandlerInterceptor li=new SOAPHandlerInterceptor(binding);
li.handleMessage(message);
control.verify();
SOAPMessage soapMessageNew=message.getContent(SOAPMessage.class);
Element headerElementNew=DOMUtils.getFirstElement(soapMessageNew.getSOAPHeader());
SoapVersion soapVersion=Soap11.getInstance();
assertEquals("false",headerElementNew.getAttributeNS(soapVersion.getNamespace(),"mustUnderstand"));
XMLStreamReader xmlReader=message.getContent(XMLStreamReader.class);
QName qn=xmlReader.getName();
assertEquals("sendReceiveData",qn.getLocalPart());
Iterator iter=message.getHeaders().iterator();
Element requiredHeader=null;
while (iter.hasNext()) {
Header localHdr=iter.next();
if (localHdr.getObject() instanceof Element) {
Element elem=(Element)localHdr.getObject();
if (elem.getNamespaceURI().equals("http://apache.org/hello_world_rpclit/types") && elem.getLocalName().equals("header1")) {
requiredHeader=(Element)localHdr.getObject();
break;
}
}
}
assertNotNull("Should have found header1",requiredHeader);
assertEquals("false",requiredHeader.getAttributeNS(soapVersion.getNamespace(),"mustUnderstand"));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testChangeSOAPBodyOutBound() throws Exception {
@SuppressWarnings("rawtypes") List list=new ArrayList();
list.add(new SOAPHandler(){
public boolean handleMessage( SOAPMessageContext smc){
Boolean outboundProperty=(Boolean)smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outboundProperty.booleanValue()) {
try {
smc.setMessage(prepareSOAPMessage("resources/greetMeRpcLitRespChanged.xml"));
}
catch ( Exception e) {
throw new Fault(e);
}
}
return true;
}
public boolean handleFault( SOAPMessageContext smc){
return true;
}
public Set getHeaders(){
return null;
}
public void close( MessageContext messageContext){
}
}
);
HandlerChainInvoker invoker=new HandlerChainInvoker(list);
IMocksControl control=createNiceControl();
Binding binding=control.createMock(Binding.class);
expect(binding.getHandlerChain()).andReturn(list).anyTimes();
Exchange exchange=control.createMock(Exchange.class);
expect(exchange.get(HandlerChainInvoker.class)).andReturn(invoker).anyTimes();
SoapMessage message=new SoapMessage(new MessageImpl());
message.setExchange(exchange);
expect(exchange.getOutMessage()).andReturn(message).anyTimes();
CachedStream originalEmptyOs=new CachedStream();
XMLStreamWriter writer=StaxUtils.createXMLStreamWriter(originalEmptyOs);
message.setContent(XMLStreamWriter.class,writer);
InterceptorChain chain=new PhaseInterceptorChain((new PhaseManagerImpl()).getOutPhases());
chain.add(new AbstractProtocolHandlerInterceptor(binding,Phase.MARSHAL){
public void handleMessage( SoapMessage message) throws Fault {
try {
XMLStreamWriter writer=message.getContent(XMLStreamWriter.class);
SoapVersion soapVersion=Soap11.getInstance();
writer.setPrefix("soap",soapVersion.getNamespace());
writer.writeStartElement("soap",soapVersion.getEnvelope().getLocalPart(),soapVersion.getNamespace());
writer.writeNamespace("soap",soapVersion.getNamespace());
writer.writeEndElement();
writer.flush();
}
catch ( Exception e) {
}
}
}
);
chain.add(new SOAPHandlerInterceptor(binding));
message.setInterceptorChain(chain);
control.replay();
chain.doIntercept(message);
control.verify();
writer.flush();
SOAPMessage resultedMessage=message.getContent(SOAPMessage.class);
assertNotNull(resultedMessage);
SOAPBody bodyNew=resultedMessage.getSOAPBody();
Iterator> itNew=bodyNew.getChildElements(new QName("http://apache.org/hello_world_rpclit","sendReceiveDataResponse"));
SOAPBodyElement bodyElementNew=(SOAPBodyElement)itNew.next();
Iterator> outIt=bodyElementNew.getChildElements(new QName("http://apache.org/hello_world_rpclit/types","out"));
Element outElement=(SOAPElement)outIt.next();
assertNotNull(outElement);
Element elem3Element=DOMUtils.findAllElementsByTagNameNS(outElement,"http://apache.org/hello_world_rpclit/types","elem3").get(0);
assertEquals("100",elem3Element.getTextContent());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetSOAPMessageInBound() throws Exception {
@SuppressWarnings("rawtypes") List list=new ArrayList();
list.add(new SOAPHandler(){
public boolean handleMessage( SOAPMessageContext smc){
try {
smc.getMessage();
}
catch ( Exception e) {
throw new Fault(e);
}
return true;
}
public boolean handleFault( SOAPMessageContext smc){
return true;
}
public Set getHeaders(){
return null;
}
public void close( MessageContext messageContext){
}
}
);
HandlerChainInvoker invoker=new HandlerChainInvoker(list);
IMocksControl control=createNiceControl();
Binding binding=control.createMock(Binding.class);
Exchange exchange=control.createMock(Exchange.class);
expect(binding.getHandlerChain()).andReturn(list).anyTimes();
expect(exchange.get(HandlerChainInvoker.class)).andReturn(invoker).anyTimes();
expect(exchange.getOutMessage()).andReturn(null);
SoapMessage message=new SoapMessage(new MessageImpl());
message.setExchange(exchange);
XMLStreamReader reader=preparemXMLStreamReader("resources/greetMeRpcLitReq.xml");
message.setContent(XMLStreamReader.class,reader);
control.replay();
SOAPHandlerInterceptor li=new SOAPHandlerInterceptor(binding);
li.handleMessage(message);
control.verify();
SOAPMessage soapMessageNew=message.getContent(SOAPMessage.class);
SOAPBody bodyNew=soapMessageNew.getSOAPBody();
Iterator> itNew=bodyNew.getChildElements();
SOAPBodyElement bodyElementNew=(SOAPBodyElement)itNew.next();
assertEquals("sendReceiveData",bodyElementNew.getLocalName());
XMLStreamReader xmlReader=message.getContent(XMLStreamReader.class);
QName qn=xmlReader.getName();
assertEquals("sendReceiveData",qn.getLocalPart());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testChangeSOAPHeaderOutBound() throws Exception {
@SuppressWarnings("rawtypes") List list=new ArrayList();
list.add(new SOAPHandler(){
public boolean handleMessage( SOAPMessageContext smc){
try {
Boolean outboundProperty=(Boolean)smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outboundProperty.booleanValue()) {
SOAPMessage message=smc.getMessage();
SOAPHeader soapHeader=message.getSOAPHeader();
Iterator> it=soapHeader.getChildElements(new QName("http://apache.org/hello_world_rpclit/types","header1"));
SOAPHeaderElement headerElementNew=(SOAPHeaderElement)it.next();
SoapVersion soapVersion=Soap11.getInstance();
Attr attr=headerElementNew.getOwnerDocument().createAttributeNS(soapVersion.getNamespace(),"SOAP-ENV:mustUnderstand");
attr.setValue("false");
headerElementNew.setAttributeNodeNS(attr);
}
}
catch ( Exception e) {
throw new Fault(e);
}
return true;
}
public boolean handleFault( SOAPMessageContext smc){
return true;
}
public Set getHeaders(){
return null;
}
public void close( MessageContext messageContext){
}
}
);
HandlerChainInvoker invoker=new HandlerChainInvoker(list);
IMocksControl control=createNiceControl();
Binding binding=control.createMock(Binding.class);
expect(binding.getHandlerChain()).andReturn(list).anyTimes();
Exchange exchange=control.createMock(Exchange.class);
expect(exchange.get(HandlerChainInvoker.class)).andReturn(invoker).anyTimes();
SoapMessage message=new SoapMessage(new MessageImpl());
message.setExchange(exchange);
expect(exchange.getOutMessage()).andReturn(message).anyTimes();
CachedStream originalEmptyOs=new CachedStream();
message.setContent(OutputStream.class,originalEmptyOs);
InterceptorChain chain=new PhaseInterceptorChain((new PhaseManagerImpl()).getOutPhases());
chain.add(new AbstractProtocolHandlerInterceptor(binding,Phase.MARSHAL){
public void handleMessage( SoapMessage message) throws Fault {
try {
XMLStreamWriter writer=message.getContent(XMLStreamWriter.class);
SoapVersion soapVersion=Soap11.getInstance();
writer.setPrefix("soap",soapVersion.getNamespace());
writer.writeStartElement("soap",soapVersion.getEnvelope().getLocalPart(),soapVersion.getNamespace());
writer.writeNamespace("soap",soapVersion.getNamespace());
Object[] headerInfo=prepareSOAPHeader();
StaxUtils.writeElement((Element)headerInfo[1],writer,true,false);
writer.writeEndElement();
writer.flush();
}
catch ( Exception e) {
}
}
}
);
chain.add(new SOAPHandlerInterceptor(binding));
message.setInterceptorChain(chain);
control.replay();
chain.doIntercept(message);
control.verify();
SOAPMessage soapMessageNew=message.getContent(SOAPMessage.class);
SOAPHeader soapHeader=soapMessageNew.getSOAPHeader();
Iterator> itNew=soapHeader.getChildElements(new QName("http://apache.org/hello_world_rpclit/types","header1"));
SOAPHeaderElement headerElementNew=(SOAPHeaderElement)itNew.next();
SoapVersion soapVersion=Soap11.getInstance();
assertEquals("false",headerElementNew.getAttributeNS(soapVersion.getNamespace(),"mustUnderstand"));
originalEmptyOs.close();
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testGetUnderstoodHeadersReturnsNull(){
@SuppressWarnings("rawtypes") List list=new ArrayList();
list.add(new SOAPHandler(){
public boolean handleMessage( SOAPMessageContext smc){
return true;
}
public boolean handleFault( SOAPMessageContext smc){
return true;
}
public Set getHeaders(){
return null;
}
public void close( MessageContext messageContext){
}
}
);
HandlerChainInvoker invoker=new HandlerChainInvoker(list);
IMocksControl control=createNiceControl();
Binding binding=control.createMock(Binding.class);
expect(binding.getHandlerChain()).andReturn(list).anyTimes();
SoapMessage message=control.createMock(SoapMessage.class);
Exchange exchange=control.createMock(Exchange.class);
expect(message.getExchange()).andReturn(exchange).anyTimes();
expect(message.keySet()).andReturn(new HashSet());
expect(exchange.get(HandlerChainInvoker.class)).andReturn(invoker);
control.replay();
SOAPHandlerInterceptor li=new SOAPHandlerInterceptor(binding);
Set understood=li.getUnderstoodHeaders();
assertNotNull(understood);
assertTrue(understood.isEmpty());
}
Class: org.apache.cxf.jaxws.header.HeaderClientServerTest IterativeVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testHeaderPartBeforeBodyPart() throws Exception {
URL wsdl=getClass().getResource("/wsdl/soapheader.wsdl");
assertNotNull(wsdl);
SOAPHeaderService service=new SOAPHeaderService(wsdl,serviceName);
assertNotNull(service);
TestHeader proxy=service.getPort(portName,TestHeader.class);
TestHeader6 in=new TestHeader6();
String val=new String(TestHeader6.class.getSimpleName());
Holder inoutHeader=new Holder();
for (int idx=0; idx < 1; idx++) {
val+=idx;
in.setRequestType(val);
inoutHeader.value=new TestHeader3();
TestHeader6Response returnVal=proxy.testHeaderPartBeforeBodyPart(inoutHeader,in);
assertNotNull(returnVal);
assertNull(returnVal.getResponseType());
assertEquals(val,inoutHeader.value.getRequestType());
in.setRequestType(null);
inoutHeader.value.setRequestType(val);
returnVal=proxy.testHeaderPartBeforeBodyPart(inoutHeader,in);
assertNotNull(returnVal);
assertEquals(val,returnVal.getResponseType());
assertNull(inoutHeader.value.getRequestType());
}
}
IterativeVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testInOutHeader() throws Exception {
URL wsdl=getClass().getResource("/wsdl/soapheader.wsdl");
assertNotNull(wsdl);
SOAPHeaderService service=new SOAPHeaderService(wsdl,serviceName);
assertNotNull(service);
TestHeader proxy=service.getPort(portName,TestHeader.class);
try {
TestHeader3 in=new TestHeader3();
String val=new String(TestHeader3.class.getSimpleName());
Holder inoutHeader=new Holder();
for (int idx=0; idx < 2; idx++) {
val+=idx;
in.setRequestType(val);
inoutHeader.value=new TestHeader3();
TestHeader3Response returnVal=proxy.testHeader3(in,inoutHeader);
assertNotNull(returnVal);
assertNull(returnVal.getResponseType());
assertEquals(val,inoutHeader.value.getRequestType());
in.setRequestType(null);
inoutHeader.value.setRequestType(val);
returnVal=proxy.testHeader3(in,inoutHeader);
assertNotNull(returnVal);
assertEquals(val,returnVal.getResponseType());
assertNull(inoutHeader.value.getRequestType());
}
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
IterativeVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testRPCInOutHeader() throws Exception {
URL wsdl=getClass().getResource("/wsdl/soapheader_rpc.wsdl");
assertNotNull(wsdl);
SOAPRPCHeaderService service=new SOAPRPCHeaderService(wsdl,new QName("http://apache.org/header_test/rpc","SOAPRPCHeaderService"));
assertNotNull(service);
TestRPCHeader proxy=service.getSoapRPCHeaderPort();
try {
HeaderMessage header=new HeaderMessage();
Holder holder=new Holder(header);
for (int idx=0; idx < 2; idx++) {
holder.value.setHeaderVal("header" + idx);
String returnVal=proxy.testInOutHeader("part" + idx,holder);
assertNotNull(returnVal);
assertEquals("header" + idx,returnVal);
assertEquals("part" + idx,holder.value.getHeaderVal());
}
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
IterativeVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testInHeader() throws Exception {
URL wsdl=getClass().getResource("/wsdl/soapheader.wsdl");
assertNotNull(wsdl);
SOAPHeaderService service=new SOAPHeaderService(wsdl,serviceName);
assertNotNull(service);
TestHeader proxy=service.getPort(portName,TestHeader.class);
try {
TestHeader1 val=new TestHeader1();
for (int idx=0; idx < 2; idx++) {
TestHeader1Response returnVal=proxy.testHeader1(val,val);
assertNotNull(returnVal);
assertEquals(TestHeader1.class.getSimpleName(),returnVal.getResponseType());
}
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testHolderOutIsTheFirstMessagePart() throws Exception {
URL wsdl=getClass().getResource("/wsdl/soapheader.wsdl");
assertNotNull(wsdl);
SOAPHeaderService service=new SOAPHeaderService(wsdl,serviceName);
assertNotNull(service);
TestHeader proxy=service.getPort(portName,TestHeader.class);
Holder simpleAll=new Holder();
SimpleAll sa=new SimpleAll();
sa.setVarAttrString("varAttrString");
sa.setVarInt(100);
sa.setVarString("varString");
simpleAll.value=sa;
SimpleChoice sc=new SimpleChoice();
sc.setVarString("scVarString");
SimpleStruct ss=proxy.sendReceiveAnyType(simpleAll,sc);
assertEquals(simpleAll.value.getVarString(),"scVarString");
assertEquals(ss.getVarInt(),200);
assertEquals(ss.getVarAttrString(),"varAttrStringRet");
}
IterativeVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testRPCInHeader() throws Exception {
URL wsdl=getClass().getResource("/wsdl/soapheader_rpc.wsdl");
assertNotNull(wsdl);
SOAPRPCHeaderService service=new SOAPRPCHeaderService(wsdl,new QName("http://apache.org/header_test/rpc","SOAPRPCHeaderService"));
assertNotNull(service);
TestRPCHeader proxy=service.getSoapRPCHeaderPort();
try {
HeaderMessage header=new HeaderMessage();
header.setHeaderVal("header");
for (int idx=0; idx < 2; idx++) {
String returnVal=proxy.testHeader1(header,"part");
assertNotNull(returnVal);
assertEquals("part/header",returnVal);
}
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testHeader7(){
URL wsdl=getClass().getResource("/wsdl/soapheader.wsdl");
assertNotNull(wsdl);
SOAPHeaderService service=new SOAPHeaderService(wsdl,serviceName);
assertNotNull(service);
TestHeader proxy=service.getPort(portName,TestHeader.class);
assertEquals("Hello",proxy.testHeader7());
}
Class: org.apache.cxf.jaxws.holder.HolderTest InternalCallVerifier EqualityVerifier
@Test public void testClient() throws Exception {
EndpointInfo ei=new EndpointInfo(null,"http://schemas.xmlsoap.org/soap/http");
ei.setAddress(address);
Destination d=localTransport.getDestination(ei,bus);
d.setMessageObserver(new MessageReplayObserver("/org/apache/cxf/jaxws/holder/echoResponse.xml"));
JaxWsProxyFactoryBean factory=new JaxWsProxyFactoryBean();
factory.getClientFactoryBean().setServiceClass(HolderService.class);
factory.getClientFactoryBean().setBus(getBus());
factory.getClientFactoryBean().setAddress(address);
HolderService h=(HolderService)factory.create();
Holder holder=new Holder();
assertEquals("one",h.echo("one","two",holder));
assertEquals("two",holder.value);
}
Class: org.apache.cxf.jaxws.provider.ProviderServiceFactoryTest BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSAAJProviderCodeFirst() throws Exception {
JaxWsServiceFactoryBean bean=new JaxWsServiceFactoryBean();
bean.setServiceClass(SAAJProvider.class);
bean.setBus(getBus());
bean.setInvoker(new JAXWSMethodInvoker(new SAAJProvider()));
Service service=bean.create();
assertEquals("SAAJProviderService",service.getName().getLocalPart());
InterfaceInfo intf=service.getServiceInfos().get(0).getInterface();
assertNotNull(intf);
assertEquals(1,intf.getOperations().size());
JaxWsServerFactoryBean svrFactory=new JaxWsServerFactoryBean();
svrFactory.setBus(getBus());
svrFactory.setServiceFactory(bean);
String address="local://localhost:9000/test";
svrFactory.setAddress(address);
ServerImpl server=(ServerImpl)svrFactory.create();
Endpoint endpoint=server.getEndpoint();
Binding binding=endpoint.getBinding();
assertTrue(binding instanceof SoapBinding);
SoapBindingInfo sb=(SoapBindingInfo)endpoint.getEndpointInfo().getBinding();
assertEquals("document",sb.getStyle());
assertEquals(false,bean.isWrapped());
assertEquals(1,sb.getOperations().size());
Node res=invoke(address,LocalTransportFactory.TRANSPORT_ID,"/org/apache/cxf/jaxws/sayHi.xml");
addNamespace("j","http://service.jaxws.cxf.apache.org/");
assertValid("/s:Envelope/s:Body/j:sayHi",res);
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSOAPBindingFromCode() throws Exception {
JaxWsServiceFactoryBean bean=new JaxWsServiceFactoryBean();
bean.setServiceClass(SOAPSourcePayloadProvider.class);
bean.setBus(getBus());
bean.setInvoker(new JAXWSMethodInvoker(new SOAPSourcePayloadProvider()));
Service service=bean.create();
assertEquals("SOAPSourcePayloadProviderService",service.getName().getLocalPart());
InterfaceInfo intf=service.getServiceInfos().get(0).getInterface();
assertNotNull(intf);
assertEquals(1,intf.getOperations().size());
JaxWsServerFactoryBean svrFactory=new JaxWsServerFactoryBean();
svrFactory.setBus(getBus());
svrFactory.setServiceFactory(bean);
String address="local://localhost:9000/test";
svrFactory.setAddress(address);
ServerImpl server=(ServerImpl)svrFactory.create();
assertEquals(1,service.getServiceInfos().get(0).getEndpoints().size());
Endpoint endpoint=server.getEndpoint();
Binding binding=endpoint.getBinding();
assertTrue(binding instanceof SoapBinding);
SoapBindingInfo sb=(SoapBindingInfo)endpoint.getEndpointInfo().getBinding();
assertEquals("document",sb.getStyle());
assertEquals(false,bean.isWrapped());
assertEquals(1,sb.getOperations().size());
Node res=invoke(address,LocalTransportFactory.TRANSPORT_ID,"/org/apache/cxf/jaxws/sayHi.xml");
addNamespace("j","http://service.jaxws.cxf.apache.org/");
assertValid("/s:Envelope/s:Body/j:sayHi",res);
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testXMLBindingFromCode() throws Exception {
JaxWsServiceFactoryBean bean=new JaxWsServiceFactoryBean();
bean.setServiceClass(DOMSourcePayloadProvider.class);
bean.setBus(getBus());
bean.setInvoker(new JAXWSMethodInvoker(new DOMSourcePayloadProvider()));
Service service=bean.create();
assertEquals("DOMSourcePayloadProviderService",service.getName().getLocalPart());
InterfaceInfo intf=service.getServiceInfos().get(0).getInterface();
assertNotNull(intf);
JaxWsServerFactoryBean svrFactory=new JaxWsServerFactoryBean();
svrFactory.setBus(getBus());
svrFactory.setServiceFactory(bean);
String address="http://localhost:9000/test";
svrFactory.setAddress(address);
svrFactory.setTransportId(LocalTransportFactory.TRANSPORT_ID);
ServerImpl server=(ServerImpl)svrFactory.create();
assertEquals(1,service.getServiceInfos().get(0).getEndpoints().size());
Endpoint endpoint=server.getEndpoint();
Binding binding=endpoint.getBinding();
assertTrue(binding instanceof XMLBinding);
Node res=invoke(address,LocalTransportFactory.TRANSPORT_ID,"/org/apache/cxf/jaxws/provider/sayHi.xml");
addNamespace("j","http://service.jaxws.cxf.apache.org/");
assertValid("/j:sayHi",res);
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testFromWSDL() throws Exception {
URL resource=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(resource);
JaxWsImplementorInfo implInfo=new JaxWsImplementorInfo(HWSoapMessageProvider.class);
JaxWsServiceFactoryBean bean=new JaxWsServiceFactoryBean(implInfo);
bean.setWsdlURL(resource.toString());
Bus bus=getBus();
bean.setBus(bus);
bean.setServiceClass(HWSoapMessageProvider.class);
Service service=bean.create();
assertTrue(service.getInvoker() instanceof JAXWSMethodInvoker);
assertEquals("SOAPService",service.getName().getLocalPart());
assertEquals("http://apache.org/hello_world_soap_http",service.getName().getNamespaceURI());
InterfaceInfo intf=service.getServiceInfos().get(0).getInterface();
assertNotNull(intf);
JaxWsServerFactoryBean svrFactory=new JaxWsServerFactoryBean();
svrFactory.setBus(bus);
svrFactory.setServiceFactory(bean);
svrFactory.setStart(false);
ServerImpl server=(ServerImpl)svrFactory.create();
assertTrue(server.getEndpoint().getService().getInvoker() instanceof JAXWSMethodInvoker);
Endpoint endpoint=server.getEndpoint();
Binding binding=endpoint.getBinding();
assertTrue(binding instanceof SoapBinding);
}
Class: org.apache.cxf.jaxws.service.AnnotationInterceptorTest BooleanVerifier InternalCallVerifier
@Test public void testJaxWsFrontendWithAnnotationInSEI() throws Exception {
jfb.setServiceClass(SayHiInterfaceImpl.class);
jfb.setServiceBean(new SayHiInterfaceImpl());
jserver=jfb.create();
List> interceptors=jserver.getEndpoint().getInInterceptors();
assertTrue(hasTestInterceptor(interceptors));
List features=jfb.getFeatures();
assertTrue(hasAnnotationFeature(features));
}
BooleanVerifier InternalCallVerifier
@Test public void testSimpleFrontend() throws Exception {
fb.setServiceClass(HelloService.class);
HelloService hello=new HelloServiceImpl();
fb.setServiceBean(hello);
server=fb.create();
List> interceptors=server.getEndpoint().getInInterceptors();
assertTrue(hasTestInterceptor(interceptors));
assertFalse(hasTest2Interceptor(interceptors));
List> outFaultInterceptors=server.getEndpoint().getOutFaultInterceptors();
assertTrue(hasTestInterceptor(outFaultInterceptors));
assertTrue(hasTest2Interceptor(outFaultInterceptors));
}
BooleanVerifier InternalCallVerifier
@Test public void testJaxwsFrontendWithNoAnnotation() throws Exception {
jfb.setServiceClass(SayHi.class);
jfb.setServiceBean(new SayHiNoInterceptor());
jserver=jfb.create();
List> interceptors=jserver.getEndpoint().getInInterceptors();
assertFalse(hasTestInterceptor(interceptors));
List features=fb.getFeatures();
assertFalse(hasAnnotationFeature(features));
}
BooleanVerifier InternalCallVerifier
@Test public void testJaxWsFrontendWithAnnotationInSEIAndImpl() throws Exception {
jfb.setServiceClass(SayHiInterface.class);
jfb.setServiceBean(new SayHiInterfaceImpl2());
jserver=jfb.create();
List> interceptors=jserver.getEndpoint().getInInterceptors();
assertFalse(hasTestInterceptor(interceptors));
assertTrue(hasTest2Interceptor(interceptors));
}
BooleanVerifier InternalCallVerifier
@Test public void testJaxwsFrontendWithAnnotationInImpl() throws Exception {
jfb.setServiceClass(SayHi.class);
SayHi implementor=new SayHiImplementation();
jfb.setServiceBean(implementor);
jserver=jfb.create();
List> interceptors=jserver.getEndpoint().getInInterceptors();
assertTrue(hasTestInterceptor(interceptors));
List> inFaultInterceptors=jserver.getEndpoint().getInFaultInterceptors();
assertFalse(hasTestInterceptor(inFaultInterceptors));
assertTrue(hasTest2Interceptor(inFaultInterceptors));
List features=jfb.getFeatures();
assertTrue(hasAnnotationFeature(features));
}
BooleanVerifier InternalCallVerifier
@Test public void testSimpleFrontendWithFeature() throws Exception {
fb.setServiceClass(HelloService.class);
HelloService hello=new HelloServiceImpl();
fb.setServiceBean(hello);
server=fb.create();
List features=fb.getFeatures();
assertTrue(hasAnnotationFeature(features));
}
BooleanVerifier InternalCallVerifier
@Test public void testJaxwsFrontendWithFeatureAnnotation() throws Exception {
jfb.setServiceClass(SayHi.class);
SayHi implementor=new SayHiImplementation();
jfb.setServiceBean(implementor);
jserver=jfb.create();
List> interceptors=jserver.getEndpoint().getInInterceptors();
assertTrue(hasAnnotationFeatureInterceptor(interceptors));
List> outInterceptors=jserver.getEndpoint().getOutInterceptors();
assertTrue(hasAnnotationFeatureInterceptor(outInterceptors));
}
BooleanVerifier InternalCallVerifier
@Test public void testSimpleFrontendWithNoAnnotation() throws Exception {
fb.setServiceClass(HelloService.class);
HelloService hello=new HelloServiceImplNoAnnotation();
fb.setServiceBean(hello);
server=fb.create();
List> interceptors=server.getEndpoint().getInInterceptors();
assertFalse(hasTestInterceptor(interceptors));
List features=fb.getFeatures();
assertFalse(hasAnnotationFeature(features));
}
Class: org.apache.cxf.jaxws.spring.SpringBeansTest UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testEndpointWithUndefinedBus() throws Exception {
try {
new ClassPathXmlApplicationContext("/org/apache/cxf/jaxws/spring/endpoints3.xml").close();
fail("Should have thrown an exception");
}
catch ( BeanCreationException ex) {
assertEquals("ep2",ex.getBeanName());
assertTrue(ex.getMessage().contains("cxf1"));
}
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCXF3959SpringInject() throws Exception {
PostConstructCalledCount.reset();
ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext("/org/apache/cxf/jaxws/spring/cxf3959c.xml");
assertNotNull(ctx);
assertEquals(2,PostConstructCalledCount.getCount());
assertEquals(0,PostConstructCalledCount.getInjectedCount());
PostConstructCalledCount pc=ctx.getBean("theBean",PostConstructCalledCount.class);
assertNotNull(pc.getContext());
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testServers() throws Exception {
ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext(new String[]{"/org/apache/cxf/jaxws/spring/servers.xml"});
JaxWsServerFactoryBean bean;
BindingConfiguration bc;
SoapBindingConfiguration sbc;
bean=(JaxWsServerFactoryBean)ctx.getBean("inlineSoapBindingRPC");
assertNotNull(bean);
bc=bean.getBindingConfig();
assertTrue(bc instanceof SoapBindingConfiguration);
sbc=(SoapBindingConfiguration)bc;
assertEquals("rpc",sbc.getStyle());
bean=(JaxWsServerFactoryBean)ctx.getBean("simple");
assertNotNull(bean);
bean=(JaxWsServerFactoryBean)ctx.getBean("inlineWsdlLocation");
assertNotNull(bean);
assertEquals(bean.getWsdlLocation(),"wsdl/hello_world_doc_lit.wsdl");
bean=(JaxWsServerFactoryBean)ctx.getBean("inlineSoapBinding");
assertNotNull(bean);
bc=bean.getBindingConfig();
assertTrue(bc instanceof SoapBindingConfiguration);
sbc=(SoapBindingConfiguration)bc;
assertTrue("Not soap version 1.2: " + sbc.getVersion(),sbc.getVersion() instanceof Soap12);
bean=(JaxWsServerFactoryBean)ctx.getBean("inlineDataBinding");
boolean found=false;
String[] names=ctx.getBeanNamesForType(SpringServerFactoryBean.class);
for ( String n : names) {
if (n.startsWith(SpringServerFactoryBean.class.getName())) {
found=true;
}
}
assertTrue("Could not find server factory with autogenerated id",found);
testNamespaceMapping(ctx);
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testClientUsingDifferentBus() throws Exception {
ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext(new String[]{"/org/apache/cxf/jaxws/spring/clients.xml"});
Greeter greeter=(Greeter)ctx.getBean("differentBusGreeter");
assertNotNull(greeter);
Client client=ClientProxy.getClient(greeter);
assertEquals("snarf",client.getBus().getProperty("foo"));
Greeter greeter1=(Greeter)ctx.getBean("client1");
assertNotNull(greeter1);
Client client1=ClientProxy.getClient(greeter1);
assertEquals("barf",client1.getBus().getProperty("foo"));
Greeter greeter2=(Greeter)ctx.getBean("wsdlLocation");
assertNotNull(greeter2);
Client client2=ClientProxy.getClient(greeter2);
assertSame(client1.getBus(),client2.getBus());
ctx.close();
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier IdentityVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testClients() throws Exception {
AbstractFactoryBeanDefinitionParser.setFactoriesAreAbstract(false);
ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext(new String[]{"/org/apache/cxf/jaxws/spring/clients.xml"});
ClientHolderBean greeters=(ClientHolderBean)ctx.getBean("greeters");
assertEquals(4,greeters.greeterCount());
Object bean=ctx.getBean("client1.proxyFactory");
assertNotNull(bean);
Greeter greeter=(Greeter)ctx.getBean("client1");
Greeter greeter2=(Greeter)ctx.getBean("client1");
assertNotNull(greeter);
assertNotNull(greeter2);
assertSame(greeter,greeter2);
Client client=ClientProxy.getClient(greeter);
assertNotNull("expected ConduitSelector",client.getConduitSelector());
assertTrue("unexpected ConduitSelector",client.getConduitSelector() instanceof NullConduitSelector);
List> inInterceptors=client.getInInterceptors();
boolean saaj=false;
boolean logging=false;
for ( Interceptor extends Message> i : inInterceptors) {
if (i instanceof SAAJInInterceptor) {
saaj=true;
}
else if (i instanceof LoggingInInterceptor) {
logging=true;
}
}
assertTrue(saaj);
assertTrue(logging);
saaj=false;
logging=false;
for ( Interceptor> i : client.getOutInterceptors()) {
if (i instanceof SAAJOutInterceptor) {
saaj=true;
}
else if (i instanceof LoggingOutInterceptor) {
logging=true;
}
}
assertTrue(saaj);
assertTrue(logging);
assertTrue(client.getEndpoint().getService().getDataBinding() instanceof SourceDataBinding);
JaxWsProxyFactoryBean factory=(JaxWsProxyFactoryBean)ctx.getBean("wsdlLocation.proxyFactory");
assertNotNull(factory);
String wsdlLocation=factory.getWsdlLocation();
assertEquals("We should get the right wsdl location",wsdlLocation,"wsdl/hello_world.wsdl");
factory=(JaxWsProxyFactoryBean)ctx.getBean("inlineSoapBinding.proxyFactory");
assertNotNull(factory);
BindingConfiguration bc=factory.getBindingConfig();
assertTrue(bc instanceof SoapBindingConfiguration);
SoapBindingConfiguration sbc=(SoapBindingConfiguration)bc;
assertTrue(sbc.getVersion() instanceof Soap12);
assertTrue("the soap configure should set isMtomEnabled to be true",sbc.isMtomEnabled());
Greeter g1=greeters.getGreet1();
Greeter g2=greeters.getGreet2();
assertNotSame(g1,g2);
ctx.close();
}
APIUtilityVerifier BranchVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testEndpoints() throws Exception {
ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext(new String[]{"/org/apache/cxf/jaxws/spring/endpoints.xml"});
EndpointImpl ep=getEndpointImplBean("simple",ctx);
assertNotNull(ep.getImplementor());
assertNotNull(ep.getServer());
ep=getEndpointImplBean("simpleWithAddress",ctx);
if (!(ep.getImplementor() instanceof org.apache.hello_world_soap_http.GreeterImpl)) {
fail("can't get the right implementor object");
}
assertEquals("http://localhost:8080/simpleWithAddress",ep.getServer().getEndpoint().getEndpointInfo().getAddress());
ep=getEndpointImplBean("inlineImplementor",ctx);
if (!(ep.getImplementor() instanceof org.apache.hello_world_soap_http.GreeterImpl)) {
fail("can't get the right implementor object");
}
org.apache.hello_world_soap_http.GreeterImpl impl=(org.apache.hello_world_soap_http.GreeterImpl)ep.getImplementor();
assertEquals("The property was not injected rightly",impl.getPrefix(),"hello");
assertNotNull(ep.getServer());
ep=getEndpointImplBean("inlineInvoker",ctx);
assertTrue(ep.getInvoker() instanceof NullInvoker);
assertTrue(ep.getService().getInvoker() instanceof NullInvoker);
ep=getEndpointImplBean("simpleWithBindingUri",ctx);
assertEquals("get the wrong bindingId",ep.getBindingUri(),"http://cxf.apache.org/bindings/xformat");
assertEquals("get a wrong transportId","http://cxf.apache.org/transports/local",ep.getTransportId());
ep=getEndpointImplBean("simpleWithBinding",ctx);
BindingConfiguration bc=ep.getBindingConfig();
assertTrue(bc instanceof SoapBindingConfiguration);
SoapBindingConfiguration sbc=(SoapBindingConfiguration)bc;
assertTrue(sbc.getVersion() instanceof Soap12);
assertTrue("the soap configure should set isMtomEnabled to be true",sbc.isMtomEnabled());
ep=getEndpointImplBean("implementorClass",ctx);
assertEquals(Hello.class,ep.getImplementorClass());
assertTrue(ep.getImplementor().getClass() == Object.class);
ep=getEndpointImplBean("epWithProps",ctx);
assertEquals("bar",ep.getProperties().get("foo"));
ep=getEndpointImplBean("classImpl",ctx);
assertTrue(ep.getImplementor() instanceof Hello);
QName name=ep.getServer().getEndpoint().getService().getName();
assertEquals("http://service.jaxws.cxf.apache.org/service",name.getNamespaceURI());
assertEquals("HelloServiceCustomized",name.getLocalPart());
name=ep.getServer().getEndpoint().getEndpointInfo().getName();
assertEquals("http://service.jaxws.cxf.apache.org/endpoint",name.getNamespaceURI());
assertEquals("HelloEndpointCustomized",name.getLocalPart());
Object bean=ctx.getBean("wsdlLocation");
assertNotNull(bean);
ep=getEndpointImplBean("publishedEndpointUrl",ctx);
String expectedEndpointUrl="http://cxf.apache.org/Greeter";
assertEquals(expectedEndpointUrl,ep.getPublishedEndpointUrl());
ep=getEndpointImplBean("epWithDataBinding",ctx);
DataBinding dataBinding=ep.getDataBinding();
assertTrue(dataBinding instanceof JAXBDataBinding);
assertEquals("The namespace map should have an entry",((JAXBDataBinding)dataBinding).getNamespaceMap().size(),1);
boolean found=false;
String[] names=ctx.getBeanNamesForType(EndpointImpl.class);
for ( String n : names) {
if (n.startsWith(EndpointImpl.class.getPackage().getName())) {
found=true;
}
}
assertTrue("Could not find server factory with autogenerated id",found);
ep=getEndpointImplBean("unpublishedEndpoint",ctx);
assertFalse("Unpublished endpoint is published",ep.isPublished());
testInterceptors(ctx);
}
InternalCallVerifier NullVerifier
@Test public void testChildContext() throws Exception {
ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext(new String[]{"/org/apache/cxf/jaxws/spring/servers.xml"});
final Bus b=(Bus)ctx.getBean("cxf");
BusLifeCycleManager lifeCycleManager=b.getExtension(BusLifeCycleManager.class);
BusLifeCycleListener listener=new BusLifeCycleListener(){
public void initComplete(){
}
public void postShutdown(){
b.setProperty("post.was.called",Boolean.TRUE);
}
public void preShutdown(){
b.setProperty("pre.was.called",Boolean.TRUE);
}
}
;
lifeCycleManager.registerLifeCycleListener(listener);
ClassPathXmlApplicationContext ctx2=new ClassPathXmlApplicationContext(new String[]{"/org/apache/cxf/jaxws/spring/child.xml"},ctx);
ctx2.close();
assertNull(b.getProperty("post.was.called"));
assertNull(b.getProperty("pre.was.called"));
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testTwoEndpointsWithTwoBuses() throws Exception {
ClassPathXmlApplicationContext ctx=null;
Bus cxf1=null;
Bus cxf2=null;
try {
ctx=new ClassPathXmlApplicationContext("/org/apache/cxf/jaxws/spring/endpoints2.xml");
EndpointImpl ep1=(EndpointImpl)ctx.getBean("ep1");
assertNotNull(ep1);
cxf1=(Bus)ctx.getBean("cxf1");
assertNotNull(cxf1);
assertEquals(cxf1,ep1.getBus());
assertEquals("barf",ep1.getBus().getProperty("foo"));
EndpointImpl ep2=(EndpointImpl)ctx.getBean("ep2");
assertNotNull(ep2);
cxf2=(Bus)ctx.getBean("cxf2");
assertNotNull(cxf2);
assertEquals(cxf2,ep2.getBus());
assertEquals("snarf",ep2.getBus().getProperty("foo"));
}
finally {
if (cxf1 != null) {
cxf1.shutdown(true);
}
if (cxf2 != null) {
cxf2.shutdown(true);
}
if (ctx != null) {
ctx.close();
}
}
}
Class: org.apache.cxf.jaxws.support.ContextPropertiesMappingTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCreateWebServiceContextWithInAttachments(){
Exchange exchange=new ExchangeImpl();
Message inMessage=new MessageImpl();
Collection attachments=new LinkedList();
DataSource source=new ByteDataSource(new byte[0],"text/xml");
DataHandler handler1=new DataHandler(source);
attachments.add(new AttachmentImpl("part1",handler1));
DataHandler handler2=new DataHandler(source);
attachments.add(new AttachmentImpl("part2",handler2));
inMessage.setAttachments(attachments);
inMessage.putAll(message);
exchange.setInMessage(inMessage);
exchange.setOutMessage(new MessageImpl());
MessageContext ctx=new WrappedMessageContext(exchange.getInMessage(),Scope.APPLICATION);
Object inAttachments=ctx.get(MessageContext.INBOUND_MESSAGE_ATTACHMENTS);
assertNotNull("inbound attachments object must be initialized",inAttachments);
assertTrue("inbound attachments must be in a Map",inAttachments instanceof Map);
Map dataHandlers=CastUtils.cast((Map,?>)inAttachments);
assertEquals("two inbound attachments expected",2,dataHandlers.size());
assertTrue("part1 attachment is missing",dataHandlers.containsKey("part1"));
assertTrue("part1 handler is missing",dataHandlers.get("part1") == handler1);
assertTrue("part2 attachment is missing",dataHandlers.containsKey("part2"));
assertTrue("part2 handler is missing",dataHandlers.get("part2") == handler2);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCreateWebServiceContext(){
Exchange exchange=new ExchangeImpl();
Message inMessage=new MessageImpl();
Message outMessage=new MessageImpl();
inMessage.putAll(message);
exchange.setInMessage(inMessage);
exchange.setOutMessage(outMessage);
MessageContext ctx=new WrappedMessageContext(exchange.getInMessage(),Scope.APPLICATION);
Object requestHeader=ctx.get(MessageContext.HTTP_REQUEST_HEADERS);
assertNotNull("the request header should not be null",requestHeader);
assertEquals("we should get the request header",requestHeader,HEADER);
Object responseHeader=ctx.get(MessageContext.HTTP_RESPONSE_HEADERS);
assertNull("the response header should be null",responseHeader);
Object outMessageHeader=outMessage.get(Message.PROTOCOL_HEADERS);
assertEquals("the outMessage PROTOCOL_HEADERS should be update",responseHeader,outMessageHeader);
Object inAttachments=ctx.get(MessageContext.INBOUND_MESSAGE_ATTACHMENTS);
assertNotNull("inbound attachments object must be initialized",inAttachments);
assertTrue("inbound attachments must be in a Map",inAttachments instanceof Map);
assertTrue("no inbound attachments expected",((Map,?>)inAttachments).isEmpty());
}
Class: org.apache.cxf.jaxws.support.JaxWsServiceConfigurationTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testDefaultStyle() throws Exception {
JaxWsServiceFactoryBean bean=new JaxWsServiceFactoryBean();
bean.setServiceClass(HelloDefault.class);
JaxWsServiceConfiguration jwsc=(JaxWsServiceConfiguration)bean.getServiceConfigurations().get(0);
jwsc.setServiceFactory(bean);
assertNull(jwsc.getStyle());
assertEquals("document",bean.getStyle());
assertNull(jwsc.isWrapped());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetOutPartName() throws Exception {
QName opName=new QName("http://cxf.com/","sayHi");
Method sayHiMethod=Hello.class.getMethod("sayHi",new Class[]{});
ServiceInfo si=getMockedServiceModel("/wsdl/default_partname_test.wsdl");
JaxWsServiceConfiguration jwsc=new JaxWsServiceConfiguration();
JaxWsServiceFactoryBean bean=new JaxWsServiceFactoryBean();
bean.setServiceClass(Hello.class);
jwsc.setServiceFactory(bean);
OperationInfo op=si.getInterface().getOperation(opName);
op.setOutput("output",new MessageInfo(op,MessageInfo.Type.OUTPUT,new QName("http://cxf.com/","output")));
QName partName=jwsc.getOutPartName(op,sayHiMethod,-1);
assertEquals("get wrong return partName",new QName("http://cxf.com/","return"),partName);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testRPCStyle() throws Exception {
JaxWsServiceFactoryBean bean=new JaxWsServiceFactoryBean();
bean.setServiceClass(HelloRPC.class);
JaxWsServiceConfiguration jwsc=(JaxWsServiceConfiguration)bean.getServiceConfigurations().get(0);
jwsc.setServiceFactory(bean);
assertEquals("rpc",jwsc.getStyle());
assertFalse(jwsc.isWrapped());
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testDocumentBareStyle() throws Exception {
JaxWsServiceFactoryBean bean=new JaxWsServiceFactoryBean();
bean.setServiceClass(HelloBare.class);
JaxWsServiceConfiguration jwsc=(JaxWsServiceConfiguration)bean.getServiceConfigurations().get(0);
jwsc.setServiceFactory(bean);
assertEquals("document",jwsc.getStyle());
assertFalse(jwsc.isWrapped());
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testDocumentWrappedStyle() throws Exception {
JaxWsServiceFactoryBean bean=new JaxWsServiceFactoryBean();
bean.setServiceClass(HelloWrapped.class);
JaxWsServiceConfiguration jwsc=(JaxWsServiceConfiguration)bean.getServiceConfigurations().get(0);
jwsc.setServiceFactory(bean);
assertEquals("document",jwsc.getStyle());
assertTrue(jwsc.isWrapped());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetInPartName() throws Exception {
QName opName=new QName("http://cxf.com/","sayHello");
Method sayHelloMethod=Hello.class.getMethod("sayHello",new Class[]{String.class,String.class});
ServiceInfo si=getMockedServiceModel("/wsdl/default_partname_test.wsdl");
JaxWsServiceFactoryBean bean=new JaxWsServiceFactoryBean();
bean.setServiceClass(Hello.class);
JaxWsServiceConfiguration jwsc=(JaxWsServiceConfiguration)bean.getServiceConfigurations().get(0);
jwsc.setServiceFactory(bean);
OperationInfo op=si.getInterface().getOperation(opName);
op.setInput("input",new MessageInfo(op,MessageInfo.Type.INPUT,new QName("http://cxf.com/","input")));
op.setOutput("output",new MessageInfo(op,MessageInfo.Type.OUTPUT,new QName("http://cxf.com/","output")));
QName partName=jwsc.getInPartName(op,sayHelloMethod,0);
assertEquals("get wrong in partName for first param",new QName("http://cxf.com/","arg0"),partName);
op.getInput().addMessagePart(new QName("arg0"));
partName=jwsc.getInPartName(op,sayHelloMethod,1);
assertEquals("get wrong in partName for first param",new QName("http://cxf.com/","arg1"),partName);
}
Class: org.apache.cxf.jaxws.support.JaxWsServiceFactoryBeanTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testWrappedDocLit() throws Exception {
ReflectionServiceFactoryBean bean=new JaxWsServiceFactoryBean();
Bus bus=getBus();
bean.setBus(bus);
bean.setServiceClass(org.apache.hello_world_doc_lit.Greeter.class);
Service service=bean.create();
ServiceInfo si=service.getServiceInfos().get(0);
InterfaceInfo intf=si.getInterface();
assertEquals(4,intf.getOperations().size());
String ns=si.getName().getNamespaceURI();
assertEquals("http://apache.org/hello_world_doc_lit",ns);
OperationInfo greetMeOp=intf.getOperation(new QName(ns,"greetMe"));
assertNotNull(greetMeOp);
assertEquals("greetMe",greetMeOp.getInput().getName().getLocalPart());
assertEquals("http://apache.org/hello_world_doc_lit",greetMeOp.getInput().getName().getNamespaceURI());
List messageParts=greetMeOp.getInput().getMessageParts();
assertEquals(1,messageParts.size());
MessagePartInfo inMessagePart=messageParts.get(0);
assertEquals("http://apache.org/hello_world_doc_lit",inMessagePart.getName().getNamespaceURI());
assertEquals("http://apache.org/hello_world_doc_lit/types",inMessagePart.getElementQName().getNamespaceURI());
messageParts=greetMeOp.getOutput().getMessageParts();
assertEquals(1,messageParts.size());
assertEquals("greetMeResponse",greetMeOp.getOutput().getName().getLocalPart());
MessagePartInfo outMessagePart=messageParts.get(0);
assertEquals("http://apache.org/hello_world_doc_lit",outMessagePart.getName().getNamespaceURI());
assertEquals("http://apache.org/hello_world_doc_lit/types",outMessagePart.getElementQName().getNamespaceURI());
OperationInfo greetMeOneWayOp=si.getInterface().getOperation(new QName(ns,"greetMeOneWay"));
assertEquals(1,greetMeOneWayOp.getInput().getMessageParts().size());
assertNull(greetMeOneWayOp.getOutput());
Collection schemas=si.getSchemas();
assertEquals(1,schemas.size());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testEndpoint() throws Exception {
ReflectionServiceFactoryBean bean=new JaxWsServiceFactoryBean();
URL resource=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(resource);
bean.setWsdlURL(resource.toString());
Bus bus=getBus();
bean.setBus(bus);
bean.setServiceClass(GreeterImpl.class);
BeanInvoker invoker=new BeanInvoker(new GreeterImpl());
bean.setInvoker(invoker);
Service service=bean.create();
String ns="http://apache.org/hello_world_soap_http";
assertEquals("SOAPService",service.getName().getLocalPart());
assertEquals(ns,service.getName().getNamespaceURI());
InterfaceInfo intf=service.getServiceInfos().get(0).getInterface();
OperationInfo op=intf.getOperation(new QName(ns,"sayHi"));
Class> wrapper=op.getInput().getMessageParts().get(0).getTypeClass();
assertNotNull(wrapper);
wrapper=op.getOutput().getMessageParts().get(0).getTypeClass();
assertNotNull(wrapper);
assertEquals(invoker,service.getInvoker());
op=intf.getOperation(new QName(ns,"testDocLitFault"));
Collection faults=op.getFaults();
assertEquals(2,faults.size());
FaultInfo f=op.getFault(new QName(ns,"BadRecordLitFault"));
assertNotNull(f);
Class> c=f.getProperty(Class.class.getName(),Class.class);
assertNotNull(c);
assertEquals(1,f.getMessageParts().size());
MessagePartInfo mpi=f.getMessagePartByIndex(0);
assertNotNull(mpi.getTypeClass());
}
BooleanVerifier InternalCallVerifier
@Test public void testMtomFeature() throws Exception {
JaxWsServiceFactoryBean bean=new JaxWsServiceFactoryBean();
bean.setBus(getBus());
bean.setServiceClass(GreeterImpl.class);
bean.setWsdlURL(getClass().getResource("/wsdl/hello_world.wsdl"));
bean.setWsFeatures(Arrays.asList(new WebServiceFeature[]{new MTOMFeature()}));
Service service=bean.create();
Endpoint endpoint=service.getEndpoints().values().iterator().next();
assertTrue(endpoint instanceof JaxWsEndpointImpl);
Binding binding=((JaxWsEndpointImpl)endpoint).getJaxwsBinding();
assertTrue(binding instanceof SOAPBinding);
assertTrue(((SOAPBinding)binding).isMTOMEnabled());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testBareBug() throws Exception {
ReflectionServiceFactoryBean bean=new JaxWsServiceFactoryBean();
Bus bus=getBus();
bean.setBus(bus);
bean.setServiceClass(org.apache.cxf.test.TestInterfacePort.class);
Service service=bean.create();
ServiceInfo si=service.getServiceInfos().get(0);
ServiceWSDLBuilder builder=new ServiceWSDLBuilder(bus,si);
Definition def=builder.build();
Document wsdl=WSDLFactory.newInstance().newWSDLWriter().getDocument(def);
NodeList nodeList=assertValid("/wsdl:definitions/wsdl:types/xsd:schema" + "[@targetNamespace='http://cxf.apache.org/" + "org.apache.cxf.test.TestInterface/xsd']"+ "/xsd:element[@name='getMessage']",wsdl);
assertEquals(1,nodeList.getLength());
assertValid("/wsdl:definitions/wsdl:message[@name='setMessage']" + "/wsdl:part[@name = 'parameters'][@element='ns1:setMessage']",wsdl);
assertValid("/wsdl:definitions/wsdl:message[@name='echoCharResponse']" + "/wsdl:part[@name = 'y'][@element='ns1:charEl_y']",wsdl);
assertValid("/wsdl:definitions/wsdl:message[@name='echoCharResponse']" + "/wsdl:part[@name = 'return'][@element='ns1:charEl_return']",wsdl);
assertValid("/wsdl:definitions/wsdl:message[@name='echoCharResponse']" + "/wsdl:part[@name = 'z'][@element='ns1:charEl_z']",wsdl);
assertValid("/wsdl:definitions/wsdl:message[@name='echoChar']" + "/wsdl:part[@name = 'x'][@element='ns1:charEl_x']",wsdl);
assertValid("/wsdl:definitions/wsdl:message[@name='echoChar']" + "/wsdl:part[@name = 'y'][@element='ns1:charEl_y']",wsdl);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testHolder() throws Exception {
ReflectionServiceFactoryBean bean=new JaxWsServiceFactoryBean();
Bus bus=getBus();
bean.setBus(bus);
bean.setServiceClass(TestMtomImpl.class);
Service service=bean.create();
InterfaceInfo intf=service.getServiceInfos().get(0).getInterface();
OperationInfo op=intf.getOperation(new QName("http://cxf.apache.org/mime","testXop"));
assertNotNull(op);
Iterator itr=op.getInput().getMessageParts().iterator();
assertTrue(itr.hasNext());
MessagePartInfo part=itr.next();
assertEquals("testXop",part.getElementQName().getLocalPart());
op=op.getUnwrappedOperation();
assertNotNull(op);
itr=op.getInput().getMessageParts().iterator();
assertTrue(itr.hasNext());
part=itr.next();
assertEquals("name",part.getName().getLocalPart());
assertEquals(String.class,part.getTypeClass());
}
APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testDocLiteralPartWithType() throws Exception {
ReflectionServiceFactoryBean serviceFactory=new JaxWsServiceFactoryBean();
serviceFactory.setBus(getBus());
serviceFactory.setServiceClass(NoBodyPartsImpl.class);
Service service=serviceFactory.create();
ServiceInfo serviceInfo=service.getServiceInfos().get(0);
QName qname=new QName("urn:org:apache:cxf:no_body_parts/wsdl","operation1");
MessageInfo mi=serviceInfo.getMessage(qname);
qname=new QName("urn:org:apache:cxf:no_body_parts/wsdl","mimeAttachment");
MessagePartInfo mpi=mi.getMessagePart(qname);
QName elementQName=mpi.getElementQName();
XmlSchemaElement element=serviceInfo.getXmlSchemaCollection().getElementByQName(elementQName);
assertNotNull(element);
}
Class: org.apache.cxf.jaxws.ws.PolicyFeatureTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testServerFactoryWith2007Xml(){
bus=new SpringBusFactory().createBus("/org/apache/cxf/jaxws/ws/server.xml");
JaxWsServerFactoryBean sf=new JaxWsServerFactoryBean();
sf.setServiceBean(new GreeterImpl());
sf.setAddress("http://localhost/test");
sf.setBus(bus);
Configurer c=bus.getExtension(Configurer.class);
c.configureBean("test",sf);
sf.setStart(false);
List features=sf.getFeatures();
assertEquals(1,features.size());
Server server=sf.create();
PolicyEngine pe=bus.getExtension(PolicyEngine.class);
assertNotNull(pe);
List sis=server.getEndpoint().getService().getServiceInfos();
ServiceInfo info=sis.get(0);
Policy p2=info.getExtensor(Policy.class);
assertNotNull(p2);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testPolicyReference(){
bus=new SpringBusFactory().createBus("/org/apache/cxf/jaxws/ws/server.xml");
JaxWsServerFactoryBean sf=new JaxWsServerFactoryBean();
sf.setServiceBean(new GreeterImpl());
sf.setAddress("http://localhost/test");
sf.setBus(bus);
Configurer c=bus.getExtension(Configurer.class);
c.configureBean("testExternal",sf);
List features=sf.getFeatures();
assertEquals(1,features.size());
sf.setStart(false);
Server server=sf.create();
PolicyEngine pe=bus.getExtension(PolicyEngine.class);
assertNotNull(pe);
List sis=server.getEndpoint().getService().getServiceInfos();
ServiceInfo info=sis.get(0);
Policy p=info.getExtensor(Policy.class);
assertNotNull(p);
assertEquals("External",p.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testServerFactory(){
bus=new CXFBusFactory().createBus();
PolicyEngineImpl pei=new PolicyEngineImpl();
bus.setExtension(pei,PolicyEngine.class);
pei.setBus(bus);
Policy p=new Policy();
p.setId("test");
JaxWsServerFactoryBean sf=new JaxWsServerFactoryBean();
sf.getFeatures().add(new WSPolicyFeature(p));
sf.setServiceBean(new GreeterImpl());
sf.setAddress("http://localhost/test");
sf.setStart(false);
sf.setBus(bus);
Server server=sf.create();
List sis=server.getEndpoint().getService().getServiceInfos();
ServiceInfo info=sis.get(0);
Policy p2=info.getExtensor(Policy.class);
assertEquals(p,p2);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testServerFactoryWith2004Xml(){
bus=new SpringBusFactory().createBus("/org/apache/cxf/jaxws/ws/server.xml");
JaxWsServerFactoryBean sf=new JaxWsServerFactoryBean();
sf.setServiceBean(new GreeterImpl());
sf.setAddress("http://localhost/test");
sf.setBus(bus);
Configurer c=bus.getExtension(Configurer.class);
c.configureBean("test2004",sf);
List extends Feature> features=sf.getFeatures();
assertEquals(1,features.size());
sf.setStart(false);
Server server=sf.create();
PolicyEngine pe=bus.getExtension(PolicyEngine.class);
assertNotNull(pe);
List sis=server.getEndpoint().getService().getServiceInfos();
ServiceInfo info=sis.get(0);
Policy p2=info.getExtensor(Policy.class);
assertNotNull(p2);
}
Class: org.apache.cxf.jca.core.classloader.PlugInClassLoaderTest InternalCallVerifier EqualityVerifier
@Test public void testLoadClassWithPlugInClassLoader() throws Exception {
Class> resultClass=plugInClassLoader.loadClass("org.apache.cxf.jca.dummy.Dummy");
assertEquals("wrong class","org.apache.cxf.jca.dummy.Dummy",resultClass.getName());
assertEquals("class loader must be the plugInClassLoader",plugInClassLoader,resultClass.getClassLoader());
}
InternalCallVerifier NullVerifier
@Test public void testLoadNonExistentDirectory() throws Exception {
URL url=plugInClassLoader.findResource("foo/bar/");
assertNull("url must be null. ",url);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testLoadSlashResourceWithPluginClassLoader() throws Exception {
Class> resultClass=plugInClassLoader.loadClass("org.apache.cxf.jca.dummy.Dummy");
URL url=resultClass.getResource("/META-INF/MANIFEST.MF");
LOG.info("URL: " + url);
assertTrue("bad url: " + url,url.toString().startsWith("classloader:"));
InputStream configStream=url.openStream();
assertNotNull("stream must not be null. ",configStream);
assertTrue("unexpected stream class: " + configStream.getClass(),configStream instanceof java.io.ByteArrayInputStream);
byte[] bytes=new byte[21];
configStream.read(bytes,0,bytes.length);
String result=IOUtils.newStringFromBytes(bytes);
LOG.fine("dummy.txt contents: " + result);
assertTrue("unexpected dummy.txt contents:" + result,result.indexOf("Manifest-Version: 1.0") != -1);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testInheritsClassLoaderProtectionDomain() throws Exception {
Class> resultClass=plugInClassLoader.loadClass("org.apache.cxf.jca.dummy.Dummy");
ProtectionDomain pd1=plugInClassLoader.getClass().getProtectionDomain();
ProtectionDomain pd2=resultClass.getProtectionDomain();
LOG.info("PluginClassLoader protection domain: " + pd1);
LOG.info("resultClass protection domain: " + pd2);
assertEquals("protection domain has to be inherited from the PluginClassLoader. ",pd1,pd2);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testLoadClassWithParentClassLoader() throws Exception {
Class> resultClass=plugInClassLoader.loadClass("org.omg.CORBA.ORB");
assertEquals("wrong class","org.omg.CORBA.ORB",resultClass.getName());
assertTrue("class loader must NOT be the plugInClassLoader",!(plugInClassLoader.equals(resultClass.getClassLoader())));
}
InternalCallVerifier NullVerifier
@Test public void testLoadNonExistentNestedDirectory() throws Exception {
URL url=plugInClassLoader.findResource("foo!/bar/");
assertNull("url must be null. ",url);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testLoadResourceWithPluginClassLoader() throws Exception {
Class> resultClass=plugInClassLoader.loadClass("org.apache.cxf.jca.dummy.Dummy");
URL url=resultClass.getResource("dummy.txt");
LOG.info("URL: " + url);
assertTrue("bad url: " + url,url.toString().startsWith("classloader:"));
InputStream configStream=url.openStream();
assertNotNull("stream must not be null. ",configStream);
assertTrue("unexpected stream class: " + configStream.getClass(),configStream instanceof java.io.ByteArrayInputStream);
byte[] bytes=new byte[10];
configStream.read(bytes,0,bytes.length);
String result=IOUtils.newStringFromBytes(bytes);
LOG.fine("dummy.txt contents: " + result);
assertEquals("unexpected dummy.txt contents.","blah,blah.",result);
}
UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testLoadNonFilteredButAvailableClassWithPlugInClassLoader() throws Exception {
String className="javax.resource.ResourceException";
getClass().getClassLoader().loadClass(className);
try {
Class> claz=plugInClassLoader.loadClass(className);
assertEquals("That should be same classloader ",claz.getClassLoader(),getClass().getClassLoader());
}
catch ( ClassNotFoundException ex) {
fail("Do not Expect ClassNotFoundException");
}
}
APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testLoadNonExistentResourceWithPluginClassLoader() throws Exception {
Class> resultClass=plugInClassLoader.loadClass("org.apache.cxf.jca.dummy.Dummy");
URL url=resultClass.getResource("foo.txt");
assertNull("url must be null. ",url);
}
Class: org.apache.cxf.jca.core.resourceadapter.HandlerTest BooleanVerifier InternalCallVerifier
@Test public void testGetStreamToThisResource() throws Exception {
String urlpath=HandlerTest.class.getName().replace('.','/') + ".class";
String urls="resourceadapter:" + urlpath;
URL res=new URL(null,urls,h);
InputStream is=h.openConnection(res).getInputStream();
assertTrue("stream is not null",is != null);
}
Class: org.apache.cxf.jca.core.resourceadapter.ManagedConnectionFactoryImplTest BooleanVerifier InternalCallVerifier
@Test public void testGetSetLogWriter() throws Exception {
PrintWriter writer=EasyMock.createMock(PrintWriter.class);
writer.write(EasyMock.isA(String.class));
EasyMock.expectLastCall().anyTimes();
writer.flush();
EasyMock.expectLastCall().anyTimes();
writer.close();
EasyMock.expectLastCall().anyTimes();
EasyMock.replay(writer);
mcf.setLogWriter(writer);
assertTrue(mcf.getLogWriter() == writer);
EasyMock.verify(writer);
}
InternalCallVerifier EqualityVerifier
@Test public void testMatchConnectionSameConnectioRequestInfoBound() throws Exception {
Subject subject=null;
Set connectionSet=new HashSet();
ConnectionRequestInfo cri=new DummyConnectionRequestInfo();
DummyManagedConnectionImpl con1=new DummyManagedConnectionImpl(mcf,cri,subject);
con1.setBound(true);
connectionSet.add(con1);
ManagedConnection mcon=mcf.matchManagedConnections(connectionSet,subject,cri);
assertEquals(con1,mcon);
}
InternalCallVerifier EqualityVerifier
@Test public void testMatchConnectionSameConnectioRequestInfoNotBound() throws Exception {
Subject subject=null;
Set connectionSet=new HashSet();
ConnectionRequestInfo cri=new DummyConnectionRequestInfo();
DummyManagedConnectionImpl con1=new DummyManagedConnectionImpl(mcf,cri,subject);
connectionSet.add(con1);
ManagedConnection mcon=mcf.matchManagedConnections(connectionSet,subject,cri);
assertEquals(con1,mcon);
}
BooleanVerifier InternalCallVerifier
@Test public void testMatchConnectionDifferentConnectioRequestInfoBound() throws Exception {
ConnectionRequestInfo cri1=new DummyConnectionRequestInfo();
ConnectionRequestInfo cri2=new DummyConnectionRequestInfo();
Subject subject=null;
assertTrue("request info object are differnt",cri1 != cri2);
Set connectionSet=new HashSet();
DummyManagedConnectionImpl con1=new DummyManagedConnectionImpl(mcf,cri1,subject);
con1.setBound(true);
connectionSet.add(con1);
ManagedConnection mcon=mcf.matchManagedConnections(connectionSet,subject,cri2);
assertTrue("should not get a match",mcon == null);
}
BooleanVerifier InternalCallVerifier
@Test public void testMatchConnectionInvalidatedWithSameConnectioRequestInfo() throws Exception {
Subject subject=null;
Set connectionSet=new HashSet();
ConnectionRequestInfo cri=new DummyConnectionRequestInfo();
DummyManagedConnectionImpl con1=new DummyManagedConnectionImpl(mcf,cri,subject);
con1.setBound(true);
con1.setCon(connectionSet);
connectionSet.add(con1);
ManagedConnection mcon=mcf.matchManagedConnections(connectionSet,subject,cri);
assertTrue("Connection must be null",mcon == null);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testMatchConnectionDifferentConnectioRequestInfoNotBound() throws Exception {
ConnectionRequestInfo cri1=new DummyConnectionRequestInfo();
ConnectionRequestInfo cri2=new DummyConnectionRequestInfo();
Subject subject=null;
assertTrue("request info object are differnt",cri1 != cri2);
Set connectionSet=new HashSet();
DummyManagedConnectionImpl con1=new DummyManagedConnectionImpl(mcf,cri1,subject);
connectionSet.add(con1);
ManagedConnection mcon=mcf.matchManagedConnections(connectionSet,subject,cri2);
assertEquals("incorrect connection returned",con1,mcon);
}
Class: org.apache.cxf.jca.core.resourceadapter.ManagedConnectionImplTest InternalCallVerifier EqualityVerifier
@Test public void testGetSetConnectionRequestInfo(){
ConnectionRequestInfo ri=new ConnectionRequestInfo(){
}
;
mc.setConnectionRequestInfo(ri);
assertEquals("Got back what we set",ri,mc.getConnectionRequestInfo());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetSetSubject(){
Subject s=new Subject();
mc.setSubject(s);
assertEquals("Got back what we set",s,mc.getSubject());
}
BooleanVerifier InternalCallVerifier
@Test public void testGetSetLogWriter() throws Exception {
PrintWriter writer=EasyMock.createMock(PrintWriter.class);
mc.setLogWriter(writer);
assertTrue(mc.getLogWriter() == writer);
writer.close();
EasyMock.expectLastCall();
EasyMock.replay(writer);
mc.destroy();
EasyMock.verify(writer);
}
Class: org.apache.cxf.jca.cxf.AssociatedManagedConnectionFactoryImplTest InternalCallVerifier EqualityVerifier
@Test public void testSetResourceAdapter() throws Exception {
TestableAssociatedManagedConnectionFactoryImpl mci=new TestableAssociatedManagedConnectionFactoryImpl();
ResourceAdapterImpl rai=new ResourceAdapterImpl();
mci.setResourceAdapter(rai);
assertEquals("ResourceAdapter is set",mci.getResourceAdapter(),rai);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testMergeNonDuplicateResourceAdapterProps() throws ResourceException {
Properties props=new Properties();
props.setProperty("key1","value1");
ResourceAdapterImpl rai=new ResourceAdapterImpl(props);
TestableAssociatedManagedConnectionFactoryImpl mci=new TestableAssociatedManagedConnectionFactoryImpl();
assertEquals("before associate, one props",0,mci.getPluginProps().size());
assertTrue("before associate, key1 not set",!mci.getPluginProps().containsKey("key1"));
mci.setResourceAdapter(rai);
assertEquals("after associate, two props",1,mci.getPluginProps().size());
assertTrue("after associate, key1 is set",mci.getPluginProps().containsKey("key1"));
}
Class: org.apache.cxf.jca.cxf.CXFConnectionRequestInfoTest BooleanVerifier InternalCallVerifier
@Test public void testCXFConnectionRequestInfoEquals() throws Exception {
CXFConnectionRequestInfo cr1=new CXFConnectionRequestInfo(Foo.class,new URL("file:/tmp/foo"),new QName("service"),new QName("fooPort"));
CXFConnectionRequestInfo cr2=new CXFConnectionRequestInfo(Foo.class,new URL("file:/tmp/foo"),new QName("service"),new QName("fooPort"));
assertTrue("Checking equals ",cr1.equals(cr2));
assertTrue("Checking hashcodes ",cr1.hashCode() == cr2.hashCode());
cr1=new CXFConnectionRequestInfo(Foo.class,null,new QName("service"),null);
cr2=new CXFConnectionRequestInfo(Foo.class,null,new QName("service"),null);
assertTrue("Checking equals with null parameters ",cr1.equals(cr2));
assertTrue("Checking hashcodes with null parameters ",cr1.hashCode() == cr2.hashCode());
cr1=new CXFConnectionRequestInfo(Foo.class,new URL("file:/tmp/foo"),new QName("service"),new QName("fooPort"));
cr2=new CXFConnectionRequestInfo(String.class,new URL("file:/tmp/foo"),new QName("service"),new QName("fooPort"));
assertTrue("Checking that objects are not equals ",!cr1.equals(cr2));
cr1=new CXFConnectionRequestInfo(Foo.class,new URL("file:/tmp/foox"),new QName("service"),new QName("fooPort"));
cr2=new CXFConnectionRequestInfo(Foo.class,new URL("file:/tmp/foo"),new QName("service"),new QName("fooPort"));
assertTrue("Checking that objects are not equal ",!cr1.equals(cr2));
cr1=new CXFConnectionRequestInfo(Foo.class,new URL("file:/tmp/foo"),new QName("service"),new QName("fooPort"));
cr2=new CXFConnectionRequestInfo(Foo.class,new URL("file:/tmp/foo"),new QName("servicex"),new QName("fooPort"));
assertTrue("Checking that objects are not equal ",!cr1.equals(cr2));
cr1=new CXFConnectionRequestInfo(Foo.class,new URL("file:/tmp/foo"),new QName("service"),new QName("fooPort"));
cr2=new CXFConnectionRequestInfo(Foo.class,new URL("file:/tmp/foo"),new QName("service"),new QName("fooPortx"));
assertTrue("Checking that objects are not equal ",!cr1.equals(cr2));
cr1=new CXFConnectionRequestInfo(Foo.class,new URL("file:/tmp/foo"),new QName("service"),new QName("fooPort"));
cr2=new CXFConnectionRequestInfo(Foo.class,null,new QName("service"),new QName("fooPort"));
assertTrue("Checking that objects are not equal ",!cr1.equals(cr2));
}
Class: org.apache.cxf.jca.cxf.ConnectionFactoryImplTest BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testInstanceOfReferencable() throws Exception {
assertTrue("Instance of Referenceable",cf instanceof Referenceable);
assertNull("No ref set",cf.getReference());
Reference ref=EasyMock.createMock(Reference.class);
cf.setReference(ref);
assertEquals("Got back what was set",ref,cf.getReference());
}
InternalCallVerifier NullVerifier
@Test public void testGetConnectionWithNoPortReturnsConnectionWithRightManager() throws Exception {
EasyMock.reset(mockConnectionManager);
CXFConnectionRequestInfo reqInfo=new CXFConnectionRequestInfo(Runnable.class,new URL("file:/tmp/foo"),new QName(""),null);
mockConnectionManager.allocateConnection(EasyMock.eq(mockConnectionFactory),EasyMock.eq(reqInfo));
EasyMock.expectLastCall().andReturn(null);
EasyMock.replay(mockConnectionManager);
param.setWsdlLocation(new URL("file:/tmp/foo"));
param.setServiceName(new QName(""));
Object o=cf.getConnection(param);
EasyMock.verify(mockConnectionManager);
assertNull("Got the result (the passed in ConnectionRequestInfo) from out mock manager",o);
}
InternalCallVerifier NullVerifier
@Test public void testGetConnectionWithNoWsdlLocationReturnsConnectionWithRightManager() throws Exception {
EasyMock.reset(mockConnectionManager);
CXFConnectionRequestInfo reqInfo=new CXFConnectionRequestInfo(Runnable.class,null,new QName(""),new QName(""));
mockConnectionManager.allocateConnection(EasyMock.eq(mockConnectionFactory),EasyMock.eq(reqInfo));
EasyMock.expectLastCall().andReturn(null);
EasyMock.replay(mockConnectionManager);
param.setServiceName(new QName(""));
param.setPortName(new QName(""));
Object o=cf.getConnection(param);
EasyMock.verify(mockConnectionManager);
assertNull("Got the result (the passed in ConnectionRequestInfo) from out mock manager",o);
}
InternalCallVerifier NullVerifier
@Test public void testGetConnectionWithNoWsdlLocationAndNoPortReturnsConnectionWithRightManager() throws Exception {
EasyMock.reset(mockConnectionManager);
CXFConnectionRequestInfo reqInfo=new CXFConnectionRequestInfo(Runnable.class,null,new QName(""),null);
mockConnectionManager.allocateConnection(EasyMock.eq(mockConnectionFactory),EasyMock.eq(reqInfo));
EasyMock.expectLastCall().andReturn(null);
EasyMock.replay(mockConnectionManager);
cf=new ConnectionFactoryImpl(mockConnectionFactory,mockConnectionManager);
param.setServiceName(new QName(""));
Object o=cf.getConnection(param);
assertNull("Got the result (the passed in ConnectionRequestInfo) from out mock manager",o);
}
InternalCallVerifier NullVerifier
@Test public void testGetConnectionReturnsConnectionWithRightManager() throws Exception {
EasyMock.reset(mockConnectionManager);
CXFConnectionRequestInfo reqInfo=new CXFConnectionRequestInfo(Runnable.class,new URL("file:/tmp/foo"),new QName(""),new QName(""));
mockConnectionManager.allocateConnection(EasyMock.eq(mockConnectionFactory),EasyMock.eq(reqInfo));
EasyMock.expectLastCall().andReturn(null);
EasyMock.replay(mockConnectionManager);
param.setWsdlLocation(new URL("file:/tmp/foo"));
param.setServiceName(new QName(""));
param.setPortName(new QName(""));
Object o=cf.getConnection(param);
assertNull("Got the result (the passed in ConnectionRequestInfo) from out mock manager",o);
EasyMock.verify(mockConnectionManager);
}
Class: org.apache.cxf.jca.cxf.JCABusFactoryTest InternalCallVerifier IdentityVerifier
@Test public void testSetAppserverClassLoader(){
ClassLoader loader=new DummyClassLoader();
JCABusFactory bf=new JCABusFactory(new ManagedConnectionFactoryImpl());
bf.setAppserverClassLoader(loader);
assertSame("Checking appserverClassLoader.",loader,bf.getAppserverClassLoader());
}
Class: org.apache.cxf.jca.cxf.ManagedConnectionFactoryImplTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testImplementsEqualsAndHashCode() throws Exception {
Method equalMethod=mci.getClass().getMethod("equals",new Class[]{Object.class});
Method hashCodeMethod=mci.getClass().getMethod("hashCode",(Class[])null);
assertTrue("not Object's equals method",equalMethod != Object.class.getDeclaredMethod("equals",new Class[]{Object.class}));
assertTrue("not Object's hashCode method",hashCodeMethod != Object.class.getDeclaredMethod("hashCode",(Class[])null));
assertEquals("equal with its self",mci,mci);
assertTrue("not equal with another",!mci.equals(new ManagedConnectionFactoryImpl()));
assertTrue("not equal with another thing",!mci.equals(this));
}
InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testMatchManagedConnectionsWithBoundConnections() throws Exception {
Subject subj=new Subject();
BusFactory bf=BusFactory.newInstance();
Bus bus=bf.createBus();
BusFactory.setDefaultBus(bus);
ManagedConnectionFactoryImpl factory=EasyMock.createMock(ManagedConnectionFactoryImpl.class);
factory.getBus();
EasyMock.expectLastCall().andReturn(bus).times(4);
EasyMock.replay(factory);
ManagedConnectionImpl mc1=new ManagedConnectionImpl(factory,cri,subj);
Object connection=mc1.getConnection(subj,cri);
assertNotNull("connection must not be null.",connection);
Set mcSet=new HashSet();
mcSet.add(mc1);
assertSame("MC1 must be selected.",mci.matchManagedConnections(mcSet,subj,cri),mc1);
bus.shutdown(true);
}
InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testMatchManagedConnectionsWithUnboundConnection() throws Exception {
mci=new ManagedConnectionFactoryImplTester();
Object unboundMC=mci.createManagedConnection(null,null);
assertNotNull("MC must not be null.",unboundMC);
Set mcSet=new HashSet();
mcSet.add(unboundMC);
assertSame("Must be same managed connection instance.",mci.matchManagedConnections(mcSet,null,cri),unboundMC);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testCreateManagedConnection() throws Exception {
ManagedConnectionFactoryImplTester mcit=new ManagedConnectionFactoryImplTester();
assertTrue("We get a ManagedConnection back",mcit.createManagedConnection(null,null) instanceof ManagedConnection);
assertEquals("init was called once",1,mcit.initCalledCount);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testSetEJBServicePropertiesPollInterval() throws Exception {
final Integer value=new Integer(10);
Properties p=new Properties();
ManagedConnectionFactoryImpl mcf=new ManagedConnectionFactoryImpl(p);
mcf.setEJBServicePropertiesPollInterval(value);
assertTrue(p.containsValue(value.toString()));
assertEquals(value,mcf.getEJBServicePropertiesPollInterval());
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testCreateConnectionFactoryCM() throws Exception {
ManagedConnectionFactoryImplTester mcit=new ManagedConnectionFactoryImplTester();
ConnectionManager connManager=EasyMock.createMock(ConnectionManager.class);
assertTrue("We get a CF back",mcit.createConnectionFactory(connManager) instanceof CXFConnectionFactory);
assertEquals("init was called once",1,mcit.initCalledCount);
}
UtilityVerifier BooleanVerifier InternalCallVerifier HybridVerifier
@Test public void testGetPropsURLFromBadURL() throws Exception {
try {
ManagedConnectionFactoryImpl mcf=new ManagedConnectionFactoryImpl();
mcf.setEJBServicePropertiesURL("rubbish_bad:/rubbish_name.properties");
mcf.getEJBServicePropertiesURLInstance();
fail("expect an exception .");
}
catch ( ResourceException re) {
assertTrue("Cause is MalformedURLException, cause: " + re.getCause(),re.getCause() instanceof MalformedURLException);
assertTrue("Error message should contains rubbish_bad",re.getMessage().indexOf("rubbish_bad") != -1);
}
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testSetMonitorEJBServiceProperties() throws Exception {
final Boolean value=Boolean.TRUE;
Properties p=new Properties();
ManagedConnectionFactoryImpl mcf=new ManagedConnectionFactoryImpl(p);
mcf.setMonitorEJBServiceProperties(value);
assertTrue(p.containsValue(value.toString()));
assertEquals(value,mcf.getMonitorEJBServiceProperties());
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testSetEJBServicePropertiesURL() throws Exception {
final String name="file://foo.txt";
Properties p=new Properties();
ManagedConnectionFactoryImpl mcf=new ManagedConnectionFactoryImpl(p);
mcf.setEJBServicePropertiesURL(name);
assertTrue(p.containsValue(name));
assertEquals(name,mcf.getEJBServicePropertiesURL());
}
Class: org.apache.cxf.jca.cxf.ManagedConnectionImplTest InternalCallVerifier EqualityVerifier
@Test public void testGetMetaData() throws Exception {
ManagedConnectionMetaData data=mci.getMetaData();
assertEquals("Checking the EISProductionVersion","1.1",data.getEISProductVersion());
assertEquals("Checking the EISProductName","WS-based-EIS",data.getEISProductName());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testAssociateConnection() throws Exception {
CXFConnectionRequestInfo cri2=new CXFConnectionRequestInfo(Greeter.class,new URL("file:/tmp/foo2"),new QName("service2"),new QName("fooPort2"));
ManagedConnectionImpl mci2=new ManagedConnectionImpl(factory,cri2,new Subject());
mci2.addConnectionEventListener(mockListener);
Object o=mci.getConnection(subj,cri);
assertTrue("Returned connection does not implement Connection interface",o instanceof Connection);
assertTrue("Returned connection does not implement Connection interface",o instanceof Greeter);
assertTrue("Returned connection is not a java.lang.reflect.Proxy instance",o instanceof Proxy);
InvocationHandler handler=Proxy.getInvocationHandler(o);
assertTrue("Asserting handler class: " + handler.getClass(),handler instanceof CXFInvocationHandler);
Object assocMci=((CXFInvocationHandler)handler).getData().getManagedConnection();
assertTrue("Asserting associated ManagedConnection.",mci == assocMci);
assertTrue("Asserting associated ManagedConnection.",mci2 != assocMci);
mci2.associateConnection(o);
assocMci=((CXFInvocationHandler)handler).getData().getManagedConnection();
assertTrue("Asserting associated ManagedConnection.",mci2 == assocMci);
assertTrue("Asserting associated ManagedConnection.",mci != assocMci);
}
Class: org.apache.cxf.jca.cxf.ResourceAdapterImplTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSerializability() throws Exception {
final String key="key";
final String value="value";
Properties props=new Properties();
props.setProperty(key,value);
ResourceAdapterImpl rai=new ResourceAdapterImpl(props);
assertTrue("before serialized, key is set",rai.getPluginProps().containsKey(key));
ByteArrayOutputStream baos=new ByteArrayOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(baos);
oos.writeObject(rai);
byte[] buf=baos.toByteArray();
oos.close();
baos.close();
ByteArrayInputStream bais=new ByteArrayInputStream(buf);
ObjectInputStream ois=new ObjectInputStream(bais);
ResourceAdapterImpl rai2=(ResourceAdapterImpl)ois.readObject();
ois.close();
bais.close();
assertNotNull("deserialized is not null",rai2);
assertTrue("props not empty",!rai2.getPluginProps().isEmpty());
assertTrue("props contains key",rai2.getPluginProps().containsKey(key));
assertEquals("no change after serialized and reconstitued ",value,rai2.getPluginProps().getProperty(key));
}
UtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testStartWithNullBootstrapContextThrowException() throws Exception {
ResourceAdapterImpl rai=new ResourceAdapterImpl();
try {
rai.start(null);
fail("Exception expected");
}
catch ( ResourceException re) {
assertTrue("error message contains BootstrapContext",re.getMessage().indexOf("BootstrapContext") != -1);
assertNull("BootstrapContext is null",rai.getBootstrapContext());
}
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetCorrectBootstrapContext() throws Exception {
ResourceAdapterImpl rai=new ResourceAdapterImpl();
BootstrapContext bc=EasyMock.createMock(BootstrapContext.class);
assertNotNull("BootstrapContext not null",bc);
rai.start(bc);
assertEquals("BootstrapContext set",rai.getBootstrapContext(),bc);
}
UtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testStopWithEmptyBusCache() throws Exception {
ResourceAdapterImpl rai=new ResourceAdapterImpl();
rai.setBusCache(new HashSet());
try {
assertNotNull("bus cache is not null",rai.getBusCache());
assertTrue("bus cache is empty",rai.getBusCache().isEmpty());
rai.stop();
}
catch ( Exception e) {
fail("no exception expected");
}
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testRegisterBusOfNull() throws Exception {
ResourceAdapterImpl rai=new ResourceAdapterImpl();
rai.registerBus(null);
assertNotNull("bus cache is not null",rai.getBusCache());
assertTrue("bus null registered",rai.getBusCache().contains(null));
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testRegisterBusNotNull() throws Exception {
ResourceAdapterImpl rai=new ResourceAdapterImpl();
Bus bus=EasyMock.createMock(Bus.class);
rai.registerBus(bus);
assertNotNull("bus cache is not null",rai.getBusCache());
assertTrue("bus registered",rai.getBusCache().contains(bus));
}
Class: org.apache.cxf.jca.cxf.handlers.AbstractInvocationHandlerTest InternalCallVerifier IdentityVerifier
@Test public void testTargetAttribute(){
CXFInvocationHandler handler=getHandler();
handler.getData().setTarget(target);
assertSame("target must be retrievable after set",target,handler.getData().getTarget());
}
InternalCallVerifier IdentityVerifier
@Test public void testManagedConnectionAttribute(){
CXFInvocationHandler handler=getHandler();
handler.getData().setManagedConnection(mockManagedConnection);
assertSame("bus must be retrievable after set",mockManagedConnection,handler.getData().getManagedConnection());
}
InternalCallVerifier IdentityVerifier
@Test public void testBusAttribute(){
CXFInvocationHandler handler=getHandler();
handler.getData().setBus(mockBus);
assertSame("bus must be retrievable after set",mockBus,handler.getData().getBus());
}
Class: org.apache.cxf.jca.cxf.handlers.InvocationHandlerFactoryTest InternalCallVerifier EqualityVerifier
@Test public void testOrderedHandlerChain() throws Exception {
assertEquals(ProxyInvocationHandler.class,handler.getClass());
assertEquals(ObjectMethodInvocationHandler.class,handler.getNext().getClass());
assertEquals(SecurityTestHandler.class,handler.getNext().getNext().getClass());
}
IterativeVerifier BooleanVerifier InternalCallVerifier IdentityVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCreateHandlerChain() throws ResourceAdapterInternalException {
CXFInvocationHandler first=handler;
CXFInvocationHandler last=null;
assertNotNull("handler must not be null",handler);
int count=0;
Set> allHandlerTypes=new HashSet>();
while (handler != null) {
assertSame("managed connection must be set",mci,handler.getData().getManagedConnection());
assertSame("bus must be set",mockBus,handler.getData().getBus());
assertSame("subject must be set",testSubject,handler.getData().getSubject());
assertSame("target must be set",target,handler.getData().getTarget());
allHandlerTypes.add(handler.getClass());
last=handler;
handler=handler.getNext();
count++;
}
assertNotNull(last);
assertEquals("must create correct number of handlers",count,4);
assertTrue("first handler must a ProxyInvocationHandler",first instanceof ProxyInvocationHandler);
assertTrue("last handler must be an InvokingInvocationHandler",last instanceof InvokingInvocationHandler);
Class>[] types={ProxyInvocationHandler.class,ObjectMethodInvocationHandler.class,InvokingInvocationHandler.class,SecurityTestHandler.class};
for (int i=0; i < types.length; i++) {
assertTrue("handler chain must contain type: " + types[i],allHandlerTypes.contains(types[i]));
}
}
Class: org.apache.cxf.jca.cxf.handlers.ObjectMethodInvocationHandlerTest BooleanVerifier InternalCallVerifier
@Test public void testToString() throws Throwable {
Method toString=Object.class.getMethod("toString",new Class[0]);
Object result=handler.invoke(testTarget,toString,null);
assertTrue("object method must not be passed to next handler in chain",!dummyHandler.invokeCalled);
assertTrue("object must be a String",result instanceof String);
assertTrue("checking toString method ",((String)result).startsWith("ConnectionHandle"));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testEqualsThroughProxies(){
Class>[] interfaces={TestInterface.class};
CXFInvocationHandlerData data1=new CXFInvocationHandlerDataImpl();
CXFInvocationHandlerData data2=new CXFInvocationHandlerDataImpl();
data1.setTarget(new TestTarget());
data2.setTarget(new TestTarget());
ObjectMethodInvocationHandler handler1=new ObjectMethodInvocationHandler(data1);
handler1.setNext(mockHandler);
ObjectMethodInvocationHandler handler2=new ObjectMethodInvocationHandler(data2);
handler2.setNext(mockHandler);
TestInterface proxy1=(TestInterface)Proxy.newProxyInstance(TestInterface.class.getClassLoader(),interfaces,handler1);
TestInterface proxy2=(TestInterface)Proxy.newProxyInstance(TestInterface.class.getClassLoader(),interfaces,handler2);
assertEquals(proxy1,proxy1);
assertTrue(!proxy1.equals(proxy2));
}
Class: org.apache.cxf.jca.outbound.ManagedConnectionImplTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
/**
* Verify the connection handle's equals() method
*/
@Test public void testHandleEqualsMethod() throws Exception {
BusFactory.setDefaultBus(null);
IMocksControl control=EasyMock.createNiceControl();
ManagedConnectionFactoryImpl mcf=control.createMock(ManagedConnectionFactoryImpl.class);
CXFConnectionSpec cxRequestInfo=new CXFConnectionSpec();
cxRequestInfo.setWsdlURL(getClass().getResource("/wsdl/hello_world.wsdl"));
cxRequestInfo.setServiceClass(Greeter.class);
cxRequestInfo.setEndpointName(new QName("http://apache.org/hello_world_soap_http","SoapPort"));
cxRequestInfo.setServiceName(new QName("http://apache.org/hello_world_soap_http","SOAPService"));
control.replay();
Subject subject=new Subject();
ManagedConnectionImpl conn=new ManagedConnectionImpl(mcf,cxRequestInfo,subject);
Object handle1=conn.getConnection(subject,cxRequestInfo);
Object handle2=conn.getConnection(subject,cxRequestInfo);
assertEquals(handle1,handle1);
assertEquals(handle2,handle2);
assertFalse(handle1.equals(handle2));
}
Class: org.apache.cxf.jca.servant.EJBEndpointTest InternalCallVerifier EqualityVerifier
@Test public void testGetAddress80Port() throws Exception {
int port=endpoint.getAddressPort("http://localhost/services");
assertEquals(80,port);
}
InternalCallVerifier EqualityVerifier
@Test public void testGetAddressPort() throws Exception {
int port=endpoint.getAddressPort("http://localhost:8080/services");
assertEquals(8080,port);
}
InternalCallVerifier EqualityVerifier
@Test public void testGetAddressEndPort() throws Exception {
int port=endpoint.getAddressPort("http://localhost:9999");
assertEquals(9999,port);
}
Class: org.apache.cxf.jca.servant.EJBServantConfigTest InternalCallVerifier NullVerifier
@Test public void testAllNull() throws Exception {
String value="";
EJBServantConfig config=new EJBServantConfig(null,value);
assertNull(config.getServiceName());
assertNull(config.getWsdlURL());
}
InternalCallVerifier EqualityVerifier
@Test public void testFullValue() throws Exception {
String value="{http://apache.org/hello_world_soap_http}SOAPService@file:/wsdl/hello_world.wsdl";
QName result=new QName("http://apache.org/hello_world_soap_http","SOAPService");
EJBServantConfig config=new EJBServantConfig(null,value);
assertEquals("file:/wsdl/hello_world.wsdl",config.getWsdlURL());
assertEquals(result,config.getServiceName());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testNoWsdl() throws Exception {
String value="{http://apache.org/hello_world_soap_http}Greeter";
QName result=new QName("http://apache.org/hello_world_soap_http","Greeter");
EJBServantConfig config=new EJBServantConfig(null,value);
assertEquals(result,config.getServiceName());
assertNull(config.getWsdlURL());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testNoWsdlNoNamespace() throws Exception {
String value="Greeter";
QName result=new QName("","Greeter");
EJBServantConfig config=new EJBServantConfig(null,value);
assertEquals(result,config.getServiceName());
assertNull(config.getWsdlURL());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testWithNullServiceName() throws Exception {
String value="@wsdl/hello_world.wsdl";
EJBServantConfig config=new EJBServantConfig(null,value);
assertNull(config.getServiceName());
assertEquals("wsdl/hello_world.wsdl",config.getWsdlURL());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testNoWsdlNoLocalPart() throws Exception {
String value="{http://apache.org/hello_world_soap_http}";
QName result=new QName("http://apache.org/hello_world_soap_http","");
EJBServantConfig config=new EJBServantConfig(null,value);
assertEquals(result,config.getServiceName());
assertNull(config.getWsdlURL());
}
InternalCallVerifier NullVerifier
@Test public void testWithNullWsdl() throws Exception {
String value="@";
EJBServantConfig config=new EJBServantConfig(null,value);
assertNull(config.getServiceName());
assertNull(config.getWsdlURL());
}
Class: org.apache.cxf.jms.testsuite.testcases.SoapJmsSpecTest APIUtilityVerifier IterativeVerifier InternalCallVerifier EqualityVerifier
@Test public void testSpecJMS() throws Exception {
QName serviceName=new QName(SERVICE_NS,"JMSGreeterService");
QName portName=new QName(SERVICE_NS,"GreeterPort");
URL wsdl=getWSDLURL(WSDL);
JMSGreeterService service=new JMSGreeterService(wsdl,serviceName);
JMSGreeterPortType greeter=markForClose(service.getPort(portName,JMSGreeterPortType.class,cff));
for (int idx=0; idx < 5; idx++) {
greeter.greetMeOneWay("test String");
String greeting=greeter.greetMe("Milestone-" + idx);
Assert.assertEquals("Hello Milestone-" + idx,greeting);
String reply=greeter.sayHi();
Assert.assertEquals(new String("Bonjour"),reply);
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testWsdlExtensionSpecJMSPortError() throws Exception {
QName serviceName=new QName(SERVICE_NS,"JMSGreeterService2");
QName portName=new QName(SERVICE_NS,"GreeterPort2");
URL wsdl=getWSDLURL(WSDL);
JMSGreeterService2 service=new JMSGreeterService2(wsdl,serviceName);
JMSGreeterPortType greeter=markForClose(service.getPort(portName,JMSGreeterPortType.class,cff));
String reply=greeter.sayHi();
Assert.assertEquals("Bonjour",reply);
}
IterativeVerifier InternalCallVerifier EqualityVerifier
@Test public void testGzip() throws Exception {
URL wsdl=getWSDLURL(WSDL);
JaxWsProxyFactoryBean factory=new JaxWsProxyFactoryBean();
factory.setBus(bus);
factory.setServiceClass(JMSGreeterPortType.class);
factory.setWsdlURL(wsdl.toExternalForm());
factory.getFeatures().add(cff);
factory.getFeatures().add(new GZIPFeature());
factory.setAddress("jms:queue:test.cxf.jmstransport.queue6");
JMSGreeterPortType greeter=(JMSGreeterPortType)markForClose(factory.create());
for (int idx=0; idx < 5; idx++) {
greeter.greetMeOneWay("test String");
String greeting=greeter.greetMe("Milestone-" + idx);
Assert.assertEquals("Hello Milestone-" + idx,greeting);
String reply=greeter.sayHi();
Assert.assertEquals("Bonjour",reply);
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testWsdlExtensionSpecJMS() throws Exception {
QName serviceName=new QName(SERVICE_NS,"JMSGreeterService");
QName portName=new QName(SERVICE_NS,"GreeterPort");
URL wsdl=getWSDLURL(WSDL);
JMSGreeterService service=new JMSGreeterService(wsdl,serviceName);
JMSGreeterPortType greeter=markForClose(service.getPort(portName,JMSGreeterPortType.class,cff));
Map requestContext=((BindingProvider)greeter).getRequestContext();
JMSMessageHeadersType requestHeader=new JMSMessageHeadersType();
requestContext.put(JMSConstants.JMS_CLIENT_REQUEST_HEADERS,requestHeader);
String reply=greeter.sayHi();
Assert.assertEquals("Bonjour",reply);
requestContext=((BindingProvider)greeter).getRequestContext();
requestHeader=(JMSMessageHeadersType)requestContext.get(JMSConstants.JMS_CLIENT_REQUEST_HEADERS);
Assert.assertEquals("1.0",requestHeader.getSOAPJMSBindingVersion());
Assert.assertEquals("\"test\"",requestHeader.getSOAPJMSSOAPAction());
Assert.assertEquals(3000,requestHeader.getTimeToLive());
Assert.assertEquals(DeliveryMode.PERSISTENT,requestHeader.getJMSDeliveryMode());
Assert.assertEquals(7,requestHeader.getJMSPriority());
Map responseContext=((BindingProvider)greeter).getResponseContext();
JMSMessageHeadersType responseHeader=(JMSMessageHeadersType)responseContext.get(JMSConstants.JMS_CLIENT_RESPONSE_HEADERS);
Assert.assertEquals("1.0",responseHeader.getSOAPJMSBindingVersion());
Assert.assertEquals(null,responseHeader.getSOAPJMSSOAPAction());
Assert.assertEquals(DeliveryMode.PERSISTENT,responseHeader.getJMSDeliveryMode());
Assert.assertEquals(7,responseHeader.getJMSPriority());
}
APIUtilityVerifier BranchVerifier UtilityVerifier BooleanVerifier InternalCallVerifier HybridVerifier
@Test public void testBindingVersionError() throws Exception {
QName serviceName=new QName(SERVICE_NS,"JMSGreeterService");
QName portName=new QName(SERVICE_NS,"GreeterPort");
URL wsdl=getWSDLURL(WSDL);
JMSGreeterService service=new JMSGreeterService(wsdl,serviceName);
JMSGreeterPortType greeter=markForClose(service.getPort(portName,JMSGreeterPortType.class,cff));
BindingProvider bp=(BindingProvider)greeter;
Map requestContext=bp.getRequestContext();
JMSMessageHeadersType requestHeader=new JMSMessageHeadersType();
requestHeader.setSOAPJMSBindingVersion("0.3");
requestContext.put(JMSConstants.JMS_CLIENT_REQUEST_HEADERS,requestHeader);
try {
greeter.greetMe("Milestone-");
Assert.fail("Should have thrown a fault");
}
catch ( SOAPFaultException ex) {
Assert.assertTrue(ex.getMessage().contains("0.3"));
Map responseContext=bp.getResponseContext();
JMSMessageHeadersType responseHdr=(JMSMessageHeadersType)responseContext.get(JMSConstants.JMS_CLIENT_RESPONSE_HEADERS);
if (responseHdr == null) {
Assert.fail("response Header should not be null");
}
Assert.assertTrue(responseHdr.isSOAPJMSIsFault());
}
}
Class: org.apache.cxf.management.InstrumentationManagerTest APIUtilityVerifier IterativeVerifier BranchVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testWorkQueueInstrumentation() throws Exception {
SpringBusFactory factory=new SpringBusFactory();
bus=factory.createBus("managed-spring.xml",true);
im=bus.getExtension(InstrumentationManager.class);
assertTrue("Instrumentation Manager should not be null",im != null);
WorkQueueManagerImpl wqm=new WorkQueueManagerImpl();
wqm.setBus(bus);
wqm.getAutomaticWorkQueue();
MBeanServer mbs=im.getMBeanServer();
assertNotNull("MBeanServer should be available.",mbs);
ObjectName name=new ObjectName(ManagementConstants.DEFAULT_DOMAIN_NAME + ":type=WorkQueues,*");
Set s=mbs.queryNames(name,null);
assertEquals(2,s.size());
Iterator it=s.iterator();
while (it.hasNext()) {
ObjectName n=it.next();
Long result=(Long)mbs.invoke(n,"getWorkQueueMaxSize",new Object[0],new String[0]);
assertEquals(result,Long.valueOf(256));
Integer hwm=(Integer)mbs.invoke(n,"getHighWaterMark",new Object[0],new String[0]);
if (n.getCanonicalName().contains("test-wq")) {
assertEquals(10,hwm.intValue());
}
else {
assertEquals(15,hwm.intValue());
}
}
bus.shutdown(true);
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testInstrumentationEnabledSetBeforeBusSet(){
SpringBusFactory factory=new SpringBusFactory();
bus=factory.createBus("managed-spring3.xml",true);
im=bus.getExtension(InstrumentationManager.class);
assertTrue("Instrumentation Manager should not be null",im != null);
MBeanServer mbs=im.getMBeanServer();
assertNotNull("MBeanServer should be available.",mbs);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testInstrumentTwoBuses(){
ClassPathXmlApplicationContext context=null;
Bus cxf1=null;
Bus cxf2=null;
try {
context=new ClassPathXmlApplicationContext("managed-spring-twobuses.xml");
cxf1=(Bus)context.getBean("cxf1");
InstrumentationManager im1=cxf1.getExtension(InstrumentationManager.class);
assertNotNull("Instrumentation Manager of cxf1 should not be null",im1);
CounterRepository cr1=cxf1.getExtension(CounterRepository.class);
assertNotNull("CounterRepository of cxf1 should not be null",cr1);
assertEquals("CounterRepository of cxf1 has the wrong bus",cxf1,cr1.getBus());
cxf2=(Bus)context.getBean("cxf2");
InstrumentationManager im2=cxf2.getExtension(InstrumentationManager.class);
assertNotNull("Instrumentation Manager of cxf2 should not be null",im2);
CounterRepository cr2=cxf2.getExtension(CounterRepository.class);
assertNotNull("CounterRepository of cxf2 should not be null",cr2);
assertEquals("CounterRepository of cxf2 has the wrong bus",cxf2,cr2.getBus());
}
finally {
if (cxf1 != null) {
cxf1.shutdown(true);
}
if (cxf2 != null) {
cxf2.shutdown(true);
}
if (context != null) {
context.close();
}
}
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testInstrumentationNotEnabled(){
SpringBusFactory factory=new SpringBusFactory();
bus=factory.createBus();
im=bus.getExtension(InstrumentationManager.class);
assertTrue("Instrumentation Manager should not be null",im != null);
MBeanServer mbs=im.getMBeanServer();
assertNull("MBeanServer should not be available.",mbs);
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testInstrumentBusWithBusProperties(){
ClassPathXmlApplicationContext context=null;
Bus cxf1=null;
Bus cxf2=null;
try {
context=new ClassPathXmlApplicationContext("managed-spring-twobuses2.xml");
cxf1=(Bus)context.getBean("cxf1");
InstrumentationManagerImpl im1=(InstrumentationManagerImpl)cxf1.getExtension(InstrumentationManager.class);
assertNotNull("Instrumentation Manager of cxf1 should not be null",im1);
assertTrue(im1.isEnabled());
assertEquals("service:jmx:rmi:///jndi/rmi://localhost:9914/jmxrmi",im1.getJMXServiceURL());
cxf2=(Bus)context.getBean("cxf2");
InstrumentationManagerImpl im2=(InstrumentationManagerImpl)cxf2.getExtension(InstrumentationManager.class);
assertNotNull("Instrumentation Manager of cxf2 should not be null",im2);
assertFalse(im2.isEnabled());
assertEquals("service:jmx:rmi:///jndi/rmi://localhost:9913/jmxrmi",im2.getJMXServiceURL());
}
finally {
if (cxf1 != null) {
cxf1.shutdown(true);
}
if (cxf2 != null) {
cxf2.shutdown(true);
}
if (context != null) {
context.close();
}
}
}
Class: org.apache.cxf.management.counters.CounterRepositoryTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testIncreaseResponseCounter() throws Exception {
MessageHandlingTimeRecorder mhtr1=EasyMock.createMock(MessageHandlingTimeRecorder.class);
EasyMock.expect(mhtr1.isOneWay()).andReturn(false).anyTimes();
EasyMock.expect(mhtr1.getHandlingTime()).andReturn((long)1000).anyTimes();
EasyMock.expect(mhtr1.getFaultMode()).andReturn(null).anyTimes();
EasyMock.replay(mhtr1);
cr.createCounter(operationCounter);
cr.increaseCounter(serviceCounter,mhtr1);
cr.increaseCounter(operationCounter,mhtr1);
ResponseTimeCounter opCounter=(ResponseTimeCounter)cr.getCounter(operationCounter);
ResponseTimeCounter sCounter=(ResponseTimeCounter)cr.getCounter(serviceCounter);
assertEquals("The operation counter isn't increased",opCounter.getNumInvocations(),1);
assertEquals("The operation counter's AvgResponseTime is wrong ",opCounter.getAvgResponseTime(),(long)1000);
assertEquals("The operation counter's MaxResponseTime is wrong ",opCounter.getMaxResponseTime(),(long)1000);
assertEquals("The operation counter's MinResponseTime is wrong ",opCounter.getMinResponseTime(),(long)1000);
assertEquals("The Service counter isn't increased",sCounter.getNumInvocations(),1);
MessageHandlingTimeRecorder mhtr2=EasyMock.createMock(MessageHandlingTimeRecorder.class);
EasyMock.expect(mhtr2.isOneWay()).andReturn(false).anyTimes();
EasyMock.expect(mhtr2.getHandlingTime()).andReturn((long)2000).anyTimes();
EasyMock.expect(mhtr2.getFaultMode()).andReturn(null).anyTimes();
EasyMock.replay(mhtr2);
cr.increaseCounter(serviceCounter,mhtr2);
cr.increaseCounter(operationCounter,mhtr2);
assertEquals("The operation counter isn't increased",opCounter.getNumInvocations(),2);
assertEquals("The operation counter's AvgResponseTime is wrong ",opCounter.getAvgResponseTime(),(long)1500);
assertEquals("The operation counter's MaxResponseTime is wrong ",opCounter.getMaxResponseTime(),(long)2000);
assertEquals("The operation counter's MinResponseTime is wrong ",opCounter.getMinResponseTime(),(long)1000);
assertEquals("The Service counter isn't increased",sCounter.getNumInvocations(),2);
opCounter.reset();
assertTrue(opCounter.getNumCheckedApplicationFaults().intValue() == 0);
assertTrue(opCounter.getNumInvocations().intValue() == 0);
assertTrue(opCounter.getNumLogicalRuntimeFaults().intValue() == 0);
assertTrue(opCounter.getNumRuntimeFaults().intValue() == 0);
assertTrue(opCounter.getNumUnCheckedApplicationFaults().intValue() == 0);
assertTrue(opCounter.getTotalHandlingTime().intValue() == 0);
assertTrue(opCounter.getMinResponseTime().intValue() == 0);
assertTrue(opCounter.getMaxResponseTime().intValue() == 0);
assertTrue(opCounter.getAvgResponseTime().intValue() == 0);
verifyBus();
EasyMock.verify(mhtr1);
EasyMock.verify(mhtr2);
}
InternalCallVerifier EqualityVerifier
@Test public void testIncreaseOneWayResponseCounter() throws Exception {
MessageHandlingTimeRecorder mhtr=EasyMock.createMock(MessageHandlingTimeRecorder.class);
EasyMock.expect(mhtr.isOneWay()).andReturn(true).anyTimes();
EasyMock.expect(mhtr.getEndTime()).andReturn((long)100000000).anyTimes();
EasyMock.expect(mhtr.getHandlingTime()).andReturn((long)1000).anyTimes();
EasyMock.expect(mhtr.getFaultMode()).andReturn(null).anyTimes();
EasyMock.replay(mhtr);
cr.increaseCounter(serviceCounter,mhtr);
cr.increaseCounter(operationCounter,mhtr);
ResponseTimeCounter opCounter=(ResponseTimeCounter)cr.getCounter(operationCounter);
ResponseTimeCounter sCounter=(ResponseTimeCounter)cr.getCounter(serviceCounter);
assertEquals("The operation counter isn't increased",opCounter.getNumInvocations(),1);
assertEquals("The Service counter isn't increased",sCounter.getNumInvocations(),1);
verifyBus();
EasyMock.verify(mhtr);
}
InternalCallVerifier EqualityVerifier
@Test public void testIncreaseOneWayNoResponseCounter() throws Exception {
MessageHandlingTimeRecorder mhtr=EasyMock.createMock(MessageHandlingTimeRecorder.class);
EasyMock.expect(mhtr.isOneWay()).andReturn(true).anyTimes();
EasyMock.expect(mhtr.getEndTime()).andReturn((long)0).anyTimes();
EasyMock.expect(mhtr.getFaultMode()).andReturn(null).anyTimes();
EasyMock.replay(mhtr);
cr.increaseCounter(serviceCounter,mhtr);
cr.increaseCounter(operationCounter,mhtr);
ResponseTimeCounter opCounter=(ResponseTimeCounter)cr.getCounter(operationCounter);
ResponseTimeCounter sCounter=(ResponseTimeCounter)cr.getCounter(serviceCounter);
assertEquals("The operation counter isn't increased",opCounter.getNumInvocations(),1);
assertEquals("The Service counter isn't increased",sCounter.getNumInvocations(),1);
verifyBus();
EasyMock.verify(mhtr);
}
Class: org.apache.cxf.management.jmx.JMXManagedComponentManagerTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testRegisterStandardMBean() throws Exception {
ObjectName name=this.registerStandardMBean("yo!");
String result=(String)manager.getMBeanServer().invoke(name,"sayHi",new Object[0],new String[0]);
assertEquals("Wazzzuuup yo!",result);
}
APIUtilityVerifier UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
/**
* Simulate repeated startup and shutdown of the CXF Bus in an environment
* where the container and MBeanServer are not shutdown between CXF restarts.
*/
@Test public void testBusLifecycleListener() throws Exception {
this.tearDown();
MBeanServer server=ManagementFactory.getPlatformMBeanServer();
this.manager=new InstrumentationManagerImpl();
this.manager.setDaemon(false);
this.manager.setThreaded(false);
this.manager.setEnabled(true);
this.manager.setJMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:" + PORT + "/jmxrmi");
this.manager.setServer(server);
this.manager.init();
ObjectName name=this.registerStandardMBean("yo!");
String result=(String)manager.getMBeanServer().invoke(name,"sayHi",new Object[0],new String[0]);
assertEquals("Wazzzuuup yo!",result);
try {
name=this.registerStandardMBean("yo!");
fail("registered duplicate MBean");
}
catch ( InstanceAlreadyExistsException e) {
}
this.manager.preShutdown();
this.manager.postShutdown();
try {
this.manager.getMBeanServer().invoke(name,"sayHi",new Object[0],new String[0]);
fail("MBean not unregistered on shutdown.");
}
catch ( InstanceNotFoundException e) {
}
this.manager=new InstrumentationManagerImpl();
this.manager.setDaemon(false);
this.manager.setThreaded(false);
this.manager.setEnabled(true);
this.manager.setJMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:" + PORT + "/jmxrmi");
this.manager.setServer(server);
this.manager.init();
name=this.registerStandardMBean("yoyo!");
result=(String)manager.getMBeanServer().invoke(name,"sayHi",new Object[0],new String[0]);
assertEquals("Wazzzuuup yoyo!",result);
}
APIUtilityVerifier UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testRegisterInstrumentation() throws Exception {
AnnotationTestInstrumentation im=new AnnotationTestInstrumentation();
ObjectName name=new ObjectName("org.apache.cxf:type=foo,name=bar");
im.setName("John Smith");
manager.register(im,name);
Object val=manager.getMBeanServer().getAttribute(name,NAME_ATTRIBUTE);
assertEquals("Incorrect result","John Smith",val);
try {
manager.register(im,name);
fail("Registering with existing name should fail.");
}
catch ( JMException jmex) {
}
manager.register(im,name,true);
val=manager.getMBeanServer().getAttribute(name,NAME_ATTRIBUTE);
assertEquals("Incorrect result","John Smith",val);
manager.unregister(name);
im.setName("Foo Bar");
name=manager.register(im);
val=manager.getMBeanServer().getAttribute(name,NAME_ATTRIBUTE);
assertEquals("Incorrect result","Foo Bar",val);
try {
manager.register(im);
fail("Registering with existing name should fail.");
}
catch ( JMException jmex) {
}
name=manager.register(im,true);
val=manager.getMBeanServer().getAttribute(name,NAME_ATTRIBUTE);
assertEquals("Incorrect result","Foo Bar",val);
manager.unregister(im);
}
Class: org.apache.cxf.management.jmx.export.ModelMBeanAssemblerTest InternalCallVerifier EqualityVerifier
@Test public void testSetAttribute() throws Exception {
getServer().setAttribute(ton,new Attribute(AGE_ATTRIBUTE,12));
assertEquals("The Age should be ",12,ati.getAge());
getServer().setAttribute(ton,new Attribute(NAME_ATTRIBUTE,"Rob Harrop"));
assertEquals("The name should be ","Rob Harrop",ati.getName());
}
Class: org.apache.cxf.management.utils.ManagementConsoleTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void paraserCommandTest(){
String[] listArgs=new String[]{"--operation","list"};
mc.parserArguments(listArgs);
assertEquals("It is not right operation name","list",mc.operationName);
assertEquals("The portName should be cleared","",mc.portName);
String[] startArgs=new String[]{"-o","start","--jmx","service:jmx:rmi:///jndi/rmi://localhost:1234/jmxrmi","--service","\"{http://apache.org/hello_world_soap_http}SOAPService\"","--port","\"{http://apache.org/hello_world_soap_http}SoapPort\""};
mc.parserArguments(startArgs);
assertEquals("It is not right operation name","start",mc.operationName);
assertEquals("It is not right port name","\"{http://apache.org/hello_world_soap_http}SoapPort\"",mc.portName);
assertEquals("It is not right service name","\"{http://apache.org/hello_world_soap_http}SOAPService\"",mc.serviceName);
assertEquals("It is not a jmx url","service:jmx:rmi:///jndi/rmi://localhost:1234/jmxrmi",mc.jmxServerURL);
String[] errorArgs=new String[]{"--op","listAll"};
assertFalse("the arguments are wrong",mc.parserArguments(errorArgs));
}
Class: org.apache.cxf.management.web.logging.ReadOnlyFileStorageTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testReadRecordsWithMultipleFiles() throws Exception {
List locations=new ArrayList();
locations.add(getClass().getResource("logs/2011-01-22-karaf.log").toURI().getPath());
locations.add(getClass().getResource("logs/2011-01-23-karaf.log").toURI().getPath());
storage.setLogLocations(locations);
List recordsFirstPage1=readPage(1,10,10);
readPage(2,10,10);
readPage(3,10,10);
List recordsPage4=readPage(4,10,10);
readPage(4,10,10);
readPage(5,10,10);
List recordsLastPage1=readPage(6,10,2);
LogRecord recordWithExceptionInMessage=recordsPage4.get(4);
assertEquals(LogLevel.ERROR,recordWithExceptionInMessage.getLevel());
assertTrue(recordWithExceptionInMessage.getMessage().contains("mvn:org.apache.cxf/cxf-bundle/"));
assertTrue(recordWithExceptionInMessage.getMessage().contains("Caused by: org.osgi.framework.BundleException"));
List recordsFirstPage2=readPage(1,10,10);
compareRecords(recordsFirstPage1,recordsFirstPage2);
List recordsLastPage2=readPage(6,10,2);
compareRecords(recordsLastPage1,recordsLastPage2);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testReadRecordsWithScanDirectory() throws Exception {
String dir=getClass().getResource("logs").toURI().getPath();
storage.setLogLocation(dir);
List recordsFirstPage1=readPage(1,10,10);
readPage(2,10,10);
readPage(3,10,10);
List recordsPage4=readPage(4,10,10);
readPage(5,10,10);
List recordsLastPage1=readPage(6,10,2);
LogRecord recordWithExceptionInMessage=recordsPage4.get(4);
assertEquals(LogLevel.ERROR,recordWithExceptionInMessage.getLevel());
assertTrue(recordWithExceptionInMessage.getMessage().contains("mvn:org.apache.cxf/cxf-bundle/"));
assertTrue(recordWithExceptionInMessage.getMessage().contains("Caused by: org.osgi.framework.BundleException"));
List recordsFirstPage2=readPage(1,10,10);
compareRecords(recordsFirstPage1,recordsFirstPage2);
List recordsLastPage2=readPage(6,10,2);
compareRecords(recordsLastPage1,recordsLastPage2);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testReadRecordsWithMultipleFilesAndSearchDates() throws Exception {
List locations=new ArrayList();
locations.add(getClass().getResource("logs/2011-01-22-karaf.log").toURI().getPath());
locations.add(getClass().getResource("logs/2011-01-23-karaf.log").toURI().getPath());
storage.setLogLocations(locations);
Map props=new HashMap();
props.put(SearchUtils.DATE_FORMAT_PROPERTY,"yyyy-MM-dd'T'HH:mm:ss SSS");
props.put(SearchUtils.TIMEZONE_SUPPORT_PROPERTY,"false");
FiqlParser parser=new FiqlParser(LogRecord.class,props);
SearchCondition sc=parser.parse("date==2011-01-22T11:49:17 184");
List recordsFirstPage1=readPage(1,sc,2,1);
List recordsFirstPage2=readPage(1,sc,2,1);
compareRecords(recordsFirstPage1,recordsFirstPage2);
LogRecord record=recordsFirstPage1.get(0);
assertEquals("Initializing Timer",record.getMessage());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testReadRecordsWithMultipleFiles2() throws Exception {
List locations=new ArrayList();
locations.add(getClass().getResource("logs/2011-01-23-karaf.log").toURI().getPath());
locations.add(getClass().getResource("logs/2011-01-22-karaf.log").toURI().getPath());
storage.setLogLocations(locations);
List recordsFirstPage1=readPage(1,10,10);
readPage(2,10,10);
readPage(3,10,10);
readPage(4,10,10);
readPage(5,10,10);
List recordsLastPage1=readPage(6,10,2);
LogRecord recordWithExceptionInMessage=recordsFirstPage1.get(2);
assertEquals(LogLevel.ERROR,recordWithExceptionInMessage.getLevel());
assertTrue(recordWithExceptionInMessage.getMessage().contains("mvn:org.apache.cxf/cxf-bundle/"));
assertTrue(recordWithExceptionInMessage.getMessage().contains("Caused by: org.osgi.framework.BundleException"));
List recordsFirstPage2=readPage(1,10,10);
compareRecords(recordsFirstPage1,recordsFirstPage2);
List recordsLastPage2=readPage(6,10,2);
compareRecords(recordsLastPage1,recordsLastPage2);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testReadRecordsWithMultipleFilesAndSearchDates2() throws Exception {
List locations=new ArrayList();
locations.add(getClass().getResource("logs/2011-01-22-karaf.log").toURI().getPath());
locations.add(getClass().getResource("logs/2011-01-23-karaf.log").toURI().getPath());
storage.setLogLocations(locations);
Map props=new HashMap();
props.put(SearchUtils.DATE_FORMAT_PROPERTY,"yyyy-MM-dd");
props.put(SearchUtils.TIMEZONE_SUPPORT_PROPERTY,"false");
FiqlParser parser=new FiqlParser(LogRecord.class,props);
SearchCondition sc=parser.parse("date=lt=2011-01-23");
List recordsFirstPage1=readPage(1,sc,32,32);
readPage(2,sc,32,0);
List recordsFirstPage2=readPage(1,sc,32,32);
compareRecords(recordsFirstPage1,recordsFirstPage2);
LogRecord firstRecord=recordsFirstPage1.get(0);
assertEquals("Starting JMX OSGi agent",firstRecord.getMessage());
LogRecord lastRecord=recordsFirstPage1.get(31);
assertTrue(lastRecord.getMessage().contains("Pax Web available at"));
readPage(2,sc,32,0);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testReadRecordsWithMultiLines() throws Exception {
storage.setLogLocation(getClass().getResource("logs/2011-01-23-karaf.log").toURI().getPath());
List recordsFirstPage1=readPage(1,10,10);
List recordsLastPage1=readPage(2,10,10);
List recordsFirstPage2=readPage(1,10,10);
compareRecords(recordsFirstPage1,recordsFirstPage2);
List recordsLastPage2=readPage(2,10,10);
compareRecords(recordsLastPage1,recordsLastPage2);
LogRecord recordWithExceptionInMessage=recordsFirstPage1.get(2);
assertEquals(LogLevel.ERROR,recordWithExceptionInMessage.getLevel());
assertTrue(recordWithExceptionInMessage.getMessage().contains("mvn:org.apache.cxf/cxf-bundle/"));
assertTrue(recordWithExceptionInMessage.getMessage().contains("Caused by: org.osgi.framework.BundleException"));
}
Class: org.apache.cxf.osgi.itests.jaxrs.JaxRsServiceTest InternalCallVerifier NullVerifier
@Test public void testJaxRsGet() throws Exception {
Book book=wt.path("/books/123").request("application/xml").get(Book.class);
Assert.assertNotNull(book);
}
InternalCallVerifier EqualityVerifier
@Test public void testJaxRsDelete() throws Exception {
Response response=wt.path("/books/123").request("application/xml").delete();
Assert.assertEquals(Status.OK.getStatusCode(),response.getStatus());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void postWithValidation() throws Exception {
Book book=new Book();
book.setId(-1);
book.setName(null);
Response response=wt.path("/books-validate/").request("application/xml").post(Entity.xml(book));
Assert.assertEquals(Status.BAD_REQUEST.getStatusCode(),response.getStatus());
book=new Book();
book.setId(3212);
book.setName("A Book");
response=wt.path("/books-validate/").request("application/xml").post(Entity.xml(book));
Assert.assertEquals(Status.CREATED.getStatusCode(),response.getStatus());
Assert.assertNotNull(response.getLocation());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testJaxRsPost() throws Exception {
Book book=new Book();
book.setId(321);
book.setName("New Book");
Response response=wt.path("/books/").request("application/xml").post(Entity.xml(book));
Assert.assertEquals(Status.CREATED.getStatusCode(),response.getStatus());
Assert.assertNotNull(response.getLocation());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testJaxRsPut() throws Exception {
Book book=new Book();
book.setId(123);
book.setName("Updated Book");
Response response=wt.path("/books/123").request("application/xml").put(Entity.xml(book));
Assert.assertEquals(Status.OK.getStatusCode(),response.getStatus());
}
Class: org.apache.cxf.osgi.itests.soap.HttpServiceTest InternalCallVerifier EqualityVerifier
@Test public void testHttpEndpointJetty() throws Exception {
Greeter greeter=greeterHttpProxy(HttpTestActivator.PORT);
String res=greeter.greetMe("Chris");
Assert.assertEquals("Hi Chris",res);
}
InternalCallVerifier EqualityVerifier
@Test public void testHttpEndpoint() throws Exception {
Greeter greeter=greeterHttpProxy("8181");
String res=greeter.greetMe("Chris");
Assert.assertEquals("Hi Chris",res);
}
Class: org.apache.cxf.osgi.itests.soap.JmsServiceTest InternalCallVerifier EqualityVerifier
@Test public void testJmsEndpoint() throws Exception {
Greeter greeter=greeterJms();
String res=greeter.greetMe("Chris");
Assert.assertEquals("Hi Chris",res);
}
Class: org.apache.cxf.phase.PhaseInterceptorChainTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testInsertionInSamePhasePass() throws Exception {
AbstractPhaseInterceptor p2=setUpPhaseInterceptor("phase1","p2");
setUpPhaseInterceptorInvocations(p2,false,false);
Set after3=new HashSet();
after3.add("p2");
AbstractPhaseInterceptor p3=setUpPhaseInterceptor("phase1","p3",null,after3);
setUpPhaseInterceptorInvocations(p3,false,false);
InsertingPhaseInterceptor p1=new InsertingPhaseInterceptor(chain,p3,"phase1","p1");
p1.addBefore("p2");
control.replay();
chain.add(p1);
chain.add(p2);
chain.doIntercept(message);
assertEquals(1,p1.invoked);
assertEquals(0,p1.faultInvoked);
}
BooleanVerifier InternalCallVerifier IdentityVerifier HybridVerifier
@Test public void testAddOneInterceptor() throws Exception {
AbstractPhaseInterceptor extends Message> p=setUpPhaseInterceptor("phase1","p1");
control.replay();
chain.add(p);
Iterator> it=chain.iterator();
assertSame(p,it.next());
assertTrue(!it.hasNext());
}
InternalCallVerifier IdentityVerifier
@Test public void testState() throws Exception {
AbstractPhaseInterceptor extends Message> p=setUpPhaseInterceptor("phase1","p1");
control.replay();
chain.add(p);
assertSame("Initial state is State.EXECUTING",InterceptorChain.State.EXECUTING,chain.getState());
chain.pause();
assertSame("Pausing chain should lead to State.PAUSED",InterceptorChain.State.PAUSED,chain.getState());
chain.resume();
assertSame("Resuming chain should lead to State.COMPLETE",InterceptorChain.State.COMPLETE,chain.getState());
chain.abort();
assertSame("Aborting chain should lead to State.ABORTED",InterceptorChain.State.ABORTED,chain.getState());
}
BooleanVerifier InternalCallVerifier IdentityVerifier HybridVerifier
@Test public void testForceAddSameInterceptor() throws Exception {
AbstractPhaseInterceptor extends Message> p=setUpPhaseInterceptor("phase1","p1");
control.replay();
chain.add(p,false);
chain.add(p,false);
Iterator> it=chain.iterator();
assertSame(p,it.next());
assertTrue(!it.hasNext());
chain.add(p,true);
it=chain.iterator();
assertSame(p,it.next());
assertSame(p,it.next());
assertTrue(!it.hasNext());
}
UtilityVerifier InternalCallVerifier IdentityVerifier HybridVerifier
@Test public void testSuspendedException() throws Exception {
CountingPhaseInterceptor p1=new CountingPhaseInterceptor("phase1","p1");
SuspendedInvocationInterceptor p2=new SuspendedInvocationInterceptor("phase2","p2");
message.getInterceptorChain();
EasyMock.expectLastCall().andReturn(chain).anyTimes();
control.replay();
chain.add(p1);
chain.add(p2);
try {
chain.doIntercept(message);
fail("Suspended invocation swallowed");
}
catch ( SuspendedInvocationException ex) {
}
assertSame("No previous interceptor selected",p1,chain.iterator().next());
assertSame("Suspended invocation should lead to State.PAUSED",InterceptorChain.State.PAUSED,chain.getState());
}
BooleanVerifier InternalCallVerifier IdentityVerifier HybridVerifier
@Test public void testForceAddSameInterceptorType() throws Exception {
AbstractPhaseInterceptor extends Message> p1=setUpPhaseInterceptor("phase1","p1");
AbstractPhaseInterceptor extends Message> p2=setUpPhaseInterceptor("phase1","p1");
control.replay();
chain.add(p1,false);
chain.add(p2,false);
Iterator> it=chain.iterator();
assertSame(p1,it.next());
assertTrue(!it.hasNext());
chain.add(p2,true);
it=chain.iterator();
assertSame(p1,it.next());
assertSame(p2,it.next());
assertTrue(!it.hasNext());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier IdentityVerifier HybridVerifier
@Test public void testThreeInterceptorSamePhaseWithOrder() throws Exception {
AbstractPhaseInterceptor extends Message> p1=setUpPhaseInterceptor("phase1","p1");
Set before=new HashSet();
before.add("p1");
AbstractPhaseInterceptor extends Message> p2=setUpPhaseInterceptor("phase1","p2",before,null);
Set before1=new HashSet();
before1.add("p2");
AbstractPhaseInterceptor extends Message> p3=setUpPhaseInterceptor("phase1","p3",before1,null);
control.replay();
chain.add(p3);
chain.add(p1);
chain.add(p2);
Iterator> it=chain.iterator();
assertSame("Unexpected interceptor at this position.",p3,it.next());
assertSame("Unexpected interceptor at this position.",p2,it.next());
assertSame("Unexpected interceptor at this position.",p1,it.next());
assertTrue(!it.hasNext());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier IdentityVerifier HybridVerifier
@Test public void testAddTwoInterceptorsSamePhase() throws Exception {
AbstractPhaseInterceptor extends Message> p1=setUpPhaseInterceptor("phase1","p1");
Set after=new HashSet();
after.add("p1");
AbstractPhaseInterceptor extends Message> p2=setUpPhaseInterceptor("phase1","p2",null,after);
control.replay();
chain.add(p1);
chain.add(p2);
Iterator> it=chain.iterator();
assertSame("Unexpected interceptor at this position.",p1,it.next());
assertSame("Unexpected interceptor at this position.",p2,it.next());
assertTrue(!it.hasNext());
}
InternalCallVerifier EqualityVerifier
@Test public void testChainInvocationStartFromSpecifiedInterceptor() throws Exception {
CountingPhaseInterceptor p1=new CountingPhaseInterceptor("phase1","p1");
CountingPhaseInterceptor p2=new CountingPhaseInterceptor("phase2","p2");
CountingPhaseInterceptor p3=new CountingPhaseInterceptor("phase3","p3");
message.getInterceptorChain();
EasyMock.expectLastCall().andReturn(chain).anyTimes();
control.replay();
chain.add(p1);
chain.add(p2);
chain.add(p3);
chain.doInterceptStartingAfter(message,p2.getId());
assertEquals(0,p1.invoked);
assertEquals(0,p2.invoked);
assertEquals(1,p3.invoked);
}
Class: org.apache.cxf.resource.ClassLoaderResolverTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetAsStream() throws IOException {
InputStream in=clr.getAsStream(resourceName);
assertNotNull(in);
BufferedReader reader=new BufferedReader(new InputStreamReader(in));
String content=reader.readLine();
assertEquals("resource content incorrect",RESOURCE_DATA,content);
}
InternalCallVerifier NullVerifier
@Test public void testResolve(){
assertNull(clr.resolve(resourceName,null));
assertNotNull(clr.resolve(resourceName,URL.class));
}
Class: org.apache.cxf.resource.URIResolverTest BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testResolvePathWithSpace() throws Exception {
URIResolver wsdlResolver=new URIResolver();
wsdlResolver.resolve(null,"wsdl/foo.wsdl",this.getClass());
assertTrue(wsdlResolver.isResolved());
String baseUri=wsdlResolver.getURI().toString();
String schemaLocation="../schemas/configuration/folder with spaces/bar.xsd";
URIResolver xsdResolver=new URIResolver();
xsdResolver.resolve(baseUri,schemaLocation,this.getClass());
assertNotNull(xsdResolver.getInputStream());
xsdResolver=new URIResolver();
xsdResolver.resolve(baseUri + "#type2",schemaLocation,this.getClass());
assertNotNull(xsdResolver.getInputStream());
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testResolveRelativeFile() throws Exception {
URIResolver wsdlResolver=new URIResolver();
wsdlResolver.resolve(null,"wsdl/foo.wsdl",this.getClass());
assertTrue(wsdlResolver.isResolved());
String baseUri=wsdlResolver.getURI().toString();
String schemaLocation="../schemas/configuration/bar.xsd";
URIResolver xsdResolver=new URIResolver();
xsdResolver.resolve(baseUri,schemaLocation,this.getClass());
assertNotNull(xsdResolver.getInputStream());
xsdResolver=new URIResolver();
xsdResolver.resolve(baseUri + "#type2",schemaLocation,this.getClass());
assertNotNull(xsdResolver.getInputStream());
}
BooleanVerifier InternalCallVerifier
@Test public void testBasePathWithEncodedSpace() throws Exception {
URIResolver wsdlResolver=new URIResolver();
wsdlResolver.resolve(null,"wsdl/folder%20with%20spaces/foo.wsdl",this.getClass());
assertTrue(wsdlResolver.isResolved());
}
APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testJARResolver() throws Exception {
uriResolver=new URIResolver();
String uriStr="jar:" + resourceURL.toString() + "!/wsdl/hello_world.wsdl";
URL jarURL=new URL(uriStr);
InputStream is=jarURL.openStream();
assertNotNull(is);
String uriStr2="jar:" + resourceURL.toString() + "!/wsdl/hello_world_2.wsdl";
URL jarURL2=new URL(uriStr2);
InputStream is2=jarURL2.openStream();
assertNotNull(is2);
uriResolver.resolve(uriStr,"hello_world_2.wsdl",null);
InputStream is3=uriResolver.getInputStream();
assertNotNull(is3);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testJARProtocol() throws Exception {
uriResolver=new URIResolver();
byte[] barray=new byte[]{0};
byte[] barray2=new byte[]{1};
String uriStr="jar:" + resourceURL.toString() + "!/wsdl/hello_world.wsdl";
URL jarURL=new URL(uriStr);
InputStream is=jarURL.openStream();
assertNotNull(is);
if (is != null) {
barray=new byte[is.available()];
is.read(barray);
is.close();
}
uriResolver.resolve("baseUriStr",uriStr,null);
InputStream is2=uriResolver.getInputStream();
assertNotNull(is2);
if (is2 != null) {
barray2=new byte[is2.available()];
is2.read(barray2);
is2.close();
}
assertEquals(IOUtils.newStringFromBytes(barray),IOUtils.newStringFromBytes(barray2));
}
BooleanVerifier InternalCallVerifier
@Test public void testBasePathWithSpace() throws Exception {
URIResolver wsdlResolver=new URIResolver();
wsdlResolver.resolve(null,"wsdl/folder with spaces/foo.wsdl",this.getClass());
assertTrue(wsdlResolver.isResolved());
}
Class: org.apache.cxf.rs.security.jose.cookbook.JwkJoseCookBookTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testPublicSetAsList() throws Exception {
JsonWebKeys jwks=readKeySet("cookbookPublicSet.txt");
List keys=jwks.getKeys();
assertEquals(2,keys.size());
JsonWebKey ecKey=keys.get(0);
assertEquals(6,ecKey.asMap().size());
validatePublicEcKey(ecKey);
JsonWebKey rsaKey=keys.get(1);
assertEquals(5,rsaKey.asMap().size());
validatePublicRsaKey(rsaKey);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testPublicSetAsMap() throws Exception {
JsonWebKeys jwks=readKeySet("cookbookPublicSet.txt");
Map> keysMap=jwks.getKeyTypeMap();
assertEquals(2,keysMap.size());
List rsaKeys=keysMap.get(KeyType.RSA);
assertEquals(1,rsaKeys.size());
assertEquals(5,rsaKeys.get(0).asMap().size());
validatePublicRsaKey(rsaKeys.get(0));
List ecKeys=keysMap.get(KeyType.EC);
assertEquals(1,ecKeys.size());
assertEquals(6,ecKeys.get(0).asMap().size());
validatePublicEcKey(ecKeys.get(0));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testSecretSetAsList() throws Exception {
JsonWebKeys jwks=readKeySet("cookbookSecretSet.txt");
List keys=jwks.getKeys();
assertEquals(2,keys.size());
JsonWebKey signKey=keys.get(0);
assertEquals(5,signKey.asMap().size());
validateSecretSignKey(signKey);
JsonWebKey encKey=keys.get(1);
assertEquals(5,encKey.asMap().size());
validateSecretEncKey(encKey);
}
Class: org.apache.cxf.rs.security.jose.cookbook.JwsJoseCookBookTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testMultipleSignatures() throws Exception {
try {
Cipher.getInstance(AlgorithmUtils.ES_SHA_512_JAVA);
}
catch ( Throwable t) {
Security.addProvider(new BouncyCastleProvider());
}
try {
JwsJsonProducer jsonProducer=new JwsJsonProducer(PAYLOAD);
assertEquals(jsonProducer.getPlainPayload(),PAYLOAD);
assertEquals(jsonProducer.getUnsignedEncodedPayload(),ENCODED_PAYLOAD);
JwsHeaders firstSignerProtectedHeader=new JwsHeaders();
firstSignerProtectedHeader.setSignatureAlgorithm(SignatureAlgorithm.RS256);
JwsHeaders firstSignerUnprotectedHeader=new JwsHeaders();
firstSignerUnprotectedHeader.setKeyId(RSA_KID_VALUE);
JsonWebKeys jwks=readKeySet("cookbookPrivateSet.txt");
List keys=jwks.getKeys();
JsonWebKey rsaKey=keys.get(1);
jsonProducer.signWith(JwsUtils.getSignatureProvider(rsaKey,SignatureAlgorithm.RS256),firstSignerProtectedHeader,firstSignerUnprotectedHeader);
assertEquals(jsonProducer.getSignatureEntries().get(0).toJson(),FIRST_SIGNATURE_ENTRY_MULTIPLE_SIGNATURES);
JwsHeaders secondSignerUnprotectedHeader=new JwsHeaders();
secondSignerUnprotectedHeader.setSignatureAlgorithm(SignatureAlgorithm.ES512);
secondSignerUnprotectedHeader.setKeyId(ECDSA_KID_VALUE);
JsonWebKey ecKey=keys.get(0);
jsonProducer.signWith(JwsUtils.getSignatureProvider(ecKey,SignatureAlgorithm.ES512),null,secondSignerUnprotectedHeader);
assertEquals(new JsonMapObjectReaderWriter().toJson(jsonProducer.getSignatureEntries().get(1).getUnprotectedHeader()),SECOND_SIGNATURE_UNPROTECTED_HEADER_MULTIPLE_SIGNATURES);
assertEquals(jsonProducer.getSignatureEntries().get(1).toJson().length(),SECOND_SIGNATURE_ENTRY_MULTIPLE_SIGNATURES.length());
JwsHeaders thirdSignerProtectedHeader=new JwsHeaders();
thirdSignerProtectedHeader.setSignatureAlgorithm(SignatureAlgorithm.HS256);
thirdSignerProtectedHeader.setKeyId(HMAC_KID_VALUE);
JsonWebKeys secretJwks=readKeySet("cookbookSecretSet.txt");
List secretKeys=secretJwks.getKeys();
JsonWebKey hmacKey=secretKeys.get(0);
jsonProducer.signWith(JwsUtils.getSignatureProvider(hmacKey,SignatureAlgorithm.HS256),thirdSignerProtectedHeader);
assertEquals(jsonProducer.getSignatureEntries().get(2).toJson(),THIRD_SIGNATURE_ENTRY_MULTIPLE_SIGNATURES);
assertEquals(jsonProducer.getJwsJsonSignedDocument().length(),MULTIPLE_SIGNATURES_JSON_GENERAL_SERIALIZATION.length());
JwsJsonConsumer jsonConsumer=new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument());
JsonWebKeys publicJwks=readKeySet("cookbookPublicSet.txt");
List publicKeys=publicJwks.getKeys();
JsonWebKey rsaPublicKey=publicKeys.get(1);
JsonWebKey ecPublicKey=publicKeys.get(0);
assertTrue(jsonConsumer.verifySignatureWith(rsaPublicKey,SignatureAlgorithm.RS256));
assertTrue(jsonConsumer.verifySignatureWith(ecPublicKey,SignatureAlgorithm.ES512));
assertTrue(jsonConsumer.verifySignatureWith(hmacKey,SignatureAlgorithm.HS256));
}
finally {
Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testRSAv15Signature() throws Exception {
JwsCompactProducer compactProducer=new JwsCompactProducer(PAYLOAD);
compactProducer.getJwsHeaders().setSignatureAlgorithm(SignatureAlgorithm.RS256);
compactProducer.getJwsHeaders().setKeyId(RSA_KID_VALUE);
JsonMapObjectReaderWriter reader=new JsonMapObjectReaderWriter();
assertEquals(reader.toJson(compactProducer.getJwsHeaders().asMap()),RSA_V1_5_SIGNATURE_PROTECTED_HEADER_JSON);
assertEquals(compactProducer.getUnsignedEncodedJws(),RSA_V1_5_SIGNATURE_PROTECTED_HEADER + "." + ENCODED_PAYLOAD);
JsonWebKeys jwks=readKeySet("cookbookPrivateSet.txt");
List keys=jwks.getKeys();
JsonWebKey rsaKey=keys.get(1);
compactProducer.signWith(rsaKey);
assertEquals(compactProducer.getSignedEncodedJws(),RSA_V1_5_SIGNATURE_PROTECTED_HEADER + "." + ENCODED_PAYLOAD+ "."+ RSA_V1_5_SIGNATURE_VALUE);
JwsCompactConsumer compactConsumer=new JwsCompactConsumer(compactProducer.getSignedEncodedJws());
JsonWebKeys publicJwks=readKeySet("cookbookPublicSet.txt");
List publicKeys=publicJwks.getKeys();
JsonWebKey rsaPublicKey=publicKeys.get(1);
assertTrue(compactConsumer.verifySignatureWith(rsaPublicKey,SignatureAlgorithm.RS256));
JwsJsonProducer jsonProducer=new JwsJsonProducer(PAYLOAD);
assertEquals(jsonProducer.getPlainPayload(),PAYLOAD);
assertEquals(jsonProducer.getUnsignedEncodedPayload(),ENCODED_PAYLOAD);
JwsHeaders protectedHeader=new JwsHeaders();
protectedHeader.setSignatureAlgorithm(SignatureAlgorithm.RS256);
protectedHeader.setKeyId(RSA_KID_VALUE);
jsonProducer.signWith(JwsUtils.getSignatureProvider(rsaKey,SignatureAlgorithm.RS256),protectedHeader);
assertEquals(jsonProducer.getJwsJsonSignedDocument(),RSA_V1_5_JSON_GENERAL_SERIALIZATION);
JwsJsonConsumer jsonConsumer=new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument());
assertTrue(jsonConsumer.verifySignatureWith(rsaPublicKey,SignatureAlgorithm.RS256));
jsonProducer=new JwsJsonProducer(PAYLOAD,true);
jsonProducer.signWith(JwsUtils.getSignatureProvider(rsaKey,SignatureAlgorithm.RS256),protectedHeader);
assertEquals(jsonProducer.getJwsJsonSignedDocument(),RSA_V1_5_JSON_FLATTENED_SERIALIZATION);
jsonConsumer=new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument());
assertTrue(jsonConsumer.verifySignatureWith(rsaPublicKey,SignatureAlgorithm.RS256));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testHMACSignature() throws Exception {
JwsCompactProducer compactProducer=new JwsCompactProducer(PAYLOAD);
compactProducer.getJwsHeaders().setSignatureAlgorithm(SignatureAlgorithm.HS256);
compactProducer.getJwsHeaders().setKeyId(HMAC_KID_VALUE);
JsonMapObjectReaderWriter reader=new JsonMapObjectReaderWriter();
assertEquals(reader.toJson(compactProducer.getJwsHeaders().asMap()),HMAC_SIGNATURE_PROTECTED_HEADER_JSON);
assertEquals(compactProducer.getUnsignedEncodedJws(),HMAC_SIGNATURE_PROTECTED_HEADER + "." + ENCODED_PAYLOAD);
JsonWebKeys jwks=readKeySet("cookbookSecretSet.txt");
List keys=jwks.getKeys();
JsonWebKey key=keys.get(0);
compactProducer.signWith(key);
assertEquals(compactProducer.getSignedEncodedJws(),HMAC_SIGNATURE_PROTECTED_HEADER + "." + ENCODED_PAYLOAD+ "."+ HMAC_SIGNATURE_VALUE);
JwsCompactConsumer compactConsumer=new JwsCompactConsumer(compactProducer.getSignedEncodedJws());
assertTrue(compactConsumer.verifySignatureWith(key,SignatureAlgorithm.HS256));
JwsJsonProducer jsonProducer=new JwsJsonProducer(PAYLOAD);
assertEquals(jsonProducer.getPlainPayload(),PAYLOAD);
assertEquals(jsonProducer.getUnsignedEncodedPayload(),ENCODED_PAYLOAD);
JwsHeaders protectedHeader=new JwsHeaders();
protectedHeader.setSignatureAlgorithm(SignatureAlgorithm.HS256);
protectedHeader.setKeyId(HMAC_KID_VALUE);
jsonProducer.signWith(JwsUtils.getSignatureProvider(key,SignatureAlgorithm.HS256),protectedHeader);
assertEquals(jsonProducer.getJwsJsonSignedDocument(),HMAC_JSON_GENERAL_SERIALIZATION);
JwsJsonConsumer jsonConsumer=new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument());
assertTrue(jsonConsumer.verifySignatureWith(key,SignatureAlgorithm.HS256));
jsonProducer=new JwsJsonProducer(PAYLOAD,true);
jsonProducer.signWith(JwsUtils.getSignatureProvider(key,SignatureAlgorithm.HS256),protectedHeader);
assertEquals(jsonProducer.getJwsJsonSignedDocument(),HMAC_JSON_FLATTENED_SERIALIZATION);
jsonConsumer=new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument());
assertTrue(jsonConsumer.verifySignatureWith(key,SignatureAlgorithm.HS256));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testRSAPSSSignature() throws Exception {
try {
Cipher.getInstance(AlgorithmUtils.PS_SHA_384_JAVA);
}
catch ( Throwable t) {
Security.addProvider(new BouncyCastleProvider());
}
JwsCompactProducer compactProducer=new JwsCompactProducer(PAYLOAD);
compactProducer.getJwsHeaders().setSignatureAlgorithm(SignatureAlgorithm.PS384);
compactProducer.getJwsHeaders().setKeyId(RSA_KID_VALUE);
JsonMapObjectReaderWriter reader=new JsonMapObjectReaderWriter();
assertEquals(reader.toJson(compactProducer.getJwsHeaders().asMap()),RSA_PSS_SIGNATURE_PROTECTED_HEADER_JSON);
assertEquals(compactProducer.getUnsignedEncodedJws(),RSA_PSS_SIGNATURE_PROTECTED_HEADER + "." + ENCODED_PAYLOAD);
JsonWebKeys jwks=readKeySet("cookbookPrivateSet.txt");
List keys=jwks.getKeys();
JsonWebKey rsaKey=keys.get(1);
compactProducer.signWith(rsaKey);
assertEquals(compactProducer.getSignedEncodedJws().length(),(RSA_PSS_SIGNATURE_PROTECTED_HEADER + "." + ENCODED_PAYLOAD+ "."+ RSA_PSS_SIGNATURE_VALUE).length());
JwsCompactConsumer compactConsumer=new JwsCompactConsumer(compactProducer.getSignedEncodedJws());
JsonWebKeys publicJwks=readKeySet("cookbookPublicSet.txt");
List publicKeys=publicJwks.getKeys();
JsonWebKey rsaPublicKey=publicKeys.get(1);
assertTrue(compactConsumer.verifySignatureWith(rsaPublicKey,SignatureAlgorithm.PS384));
JwsJsonProducer jsonProducer=new JwsJsonProducer(PAYLOAD);
assertEquals(jsonProducer.getPlainPayload(),PAYLOAD);
assertEquals(jsonProducer.getUnsignedEncodedPayload(),ENCODED_PAYLOAD);
JwsHeaders protectedHeader=new JwsHeaders();
protectedHeader.setSignatureAlgorithm(SignatureAlgorithm.PS384);
protectedHeader.setKeyId(RSA_KID_VALUE);
jsonProducer.signWith(JwsUtils.getSignatureProvider(rsaKey,SignatureAlgorithm.PS384),protectedHeader);
assertEquals(jsonProducer.getJwsJsonSignedDocument().length(),RSA_PSS_JSON_GENERAL_SERIALIZATION.length());
JwsJsonConsumer jsonConsumer=new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument());
assertTrue(jsonConsumer.verifySignatureWith(rsaPublicKey,SignatureAlgorithm.PS384));
jsonProducer=new JwsJsonProducer(PAYLOAD,true);
jsonProducer.signWith(JwsUtils.getSignatureProvider(rsaKey,SignatureAlgorithm.PS384),protectedHeader);
assertEquals(jsonProducer.getJwsJsonSignedDocument().length(),RSA_PSS_JSON_FLATTENED_SERIALIZATION.length());
jsonConsumer=new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument());
assertTrue(jsonConsumer.verifySignatureWith(rsaPublicKey,SignatureAlgorithm.PS384));
Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testDetachedHMACSignature() throws Exception {
JwsCompactProducer compactProducer=new JwsCompactProducer(PAYLOAD,true);
compactProducer.getJwsHeaders().setSignatureAlgorithm(SignatureAlgorithm.HS256);
compactProducer.getJwsHeaders().setKeyId(HMAC_KID_VALUE);
JsonMapObjectReaderWriter reader=new JsonMapObjectReaderWriter();
assertEquals(reader.toJson(compactProducer.getJwsHeaders().asMap()),HMAC_SIGNATURE_PROTECTED_HEADER_JSON);
assertEquals(compactProducer.getUnsignedEncodedJws(),HMAC_SIGNATURE_PROTECTED_HEADER + ".");
JsonWebKeys jwks=readKeySet("cookbookSecretSet.txt");
List keys=jwks.getKeys();
JsonWebKey key=keys.get(0);
compactProducer.signWith(key);
assertEquals(compactProducer.getSignedEncodedJws(),DETACHED_HMAC_JWS);
JwsCompactConsumer compactConsumer=new JwsCompactConsumer(compactProducer.getSignedEncodedJws(),ENCODED_PAYLOAD);
assertTrue(compactConsumer.verifySignatureWith(key,SignatureAlgorithm.HS256));
JwsJsonProducer jsonProducer=new JwsJsonProducer(PAYLOAD);
assertEquals(jsonProducer.getPlainPayload(),PAYLOAD);
assertEquals(jsonProducer.getUnsignedEncodedPayload(),ENCODED_PAYLOAD);
JwsHeaders protectedHeader=new JwsHeaders();
protectedHeader.setSignatureAlgorithm(SignatureAlgorithm.HS256);
protectedHeader.setKeyId(HMAC_KID_VALUE);
jsonProducer.signWith(JwsUtils.getSignatureProvider(key,SignatureAlgorithm.HS256),protectedHeader);
assertEquals(jsonProducer.getJwsJsonSignedDocument(true),HMAC_DETACHED_JSON_GENERAL_SERIALIZATION);
JwsJsonConsumer jsonConsumer=new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument(true),ENCODED_PAYLOAD);
assertTrue(jsonConsumer.verifySignatureWith(key,SignatureAlgorithm.HS256));
jsonProducer=new JwsJsonProducer(PAYLOAD,true);
jsonProducer.signWith(JwsUtils.getSignatureProvider(key,SignatureAlgorithm.HS256),protectedHeader);
assertEquals(jsonProducer.getJwsJsonSignedDocument(true),HMAC_DETACHED_JSON_FLATTENED_SERIALIZATION);
jsonConsumer=new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument(true),ENCODED_PAYLOAD);
assertTrue(jsonConsumer.verifySignatureWith(key,SignatureAlgorithm.HS256));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testProtectingSpecificHeaderFieldsSignature() throws Exception {
JwsJsonProducer jsonProducer=new JwsJsonProducer(PAYLOAD);
assertEquals(jsonProducer.getPlainPayload(),PAYLOAD);
assertEquals(jsonProducer.getUnsignedEncodedPayload(),ENCODED_PAYLOAD);
JwsHeaders protectedHeader=new JwsHeaders();
protectedHeader.setSignatureAlgorithm(SignatureAlgorithm.HS256);
JwsHeaders unprotectedHeader=new JwsHeaders();
unprotectedHeader.setKeyId(HMAC_KID_VALUE);
JsonWebKeys jwks=readKeySet("cookbookSecretSet.txt");
List keys=jwks.getKeys();
JsonWebKey key=keys.get(0);
jsonProducer.signWith(JwsUtils.getSignatureProvider(key,SignatureAlgorithm.HS256),protectedHeader,unprotectedHeader);
assertEquals(jsonProducer.getJwsJsonSignedDocument(),PROTECTING_SPECIFIC_HEADER_FIELDS_JSON_GENERAL_SERIALIZATION);
JwsJsonConsumer jsonConsumer=new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument());
assertTrue(jsonConsumer.verifySignatureWith(key,SignatureAlgorithm.HS256));
jsonProducer=new JwsJsonProducer(PAYLOAD,true);
jsonProducer.signWith(JwsUtils.getSignatureProvider(key,SignatureAlgorithm.HS256),protectedHeader,unprotectedHeader);
assertEquals(jsonProducer.getJwsJsonSignedDocument(),PROTECTING_SPECIFIC_HEADER_FIELDS_JSON_FLATTENED_SERIALIZATION);
jsonConsumer=new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument());
assertTrue(jsonConsumer.verifySignatureWith(key,SignatureAlgorithm.HS256));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testECDSASignature() throws Exception {
try {
Cipher.getInstance(AlgorithmUtils.ES_SHA_512_JAVA);
}
catch ( Throwable t) {
Security.addProvider(new BouncyCastleProvider());
}
try {
JwsCompactProducer compactProducer=new JwsCompactProducer(PAYLOAD);
compactProducer.getJwsHeaders().setSignatureAlgorithm(SignatureAlgorithm.ES512);
compactProducer.getJwsHeaders().setKeyId(ECDSA_KID_VALUE);
JsonMapObjectReaderWriter reader=new JsonMapObjectReaderWriter();
assertEquals(reader.toJson(compactProducer.getJwsHeaders().asMap()),ECDSA_SIGNATURE_PROTECTED_HEADER_JSON);
assertEquals(compactProducer.getUnsignedEncodedJws(),ECSDA_SIGNATURE_PROTECTED_HEADER + "." + ENCODED_PAYLOAD);
JsonWebKeys jwks=readKeySet("cookbookPrivateSet.txt");
List keys=jwks.getKeys();
JsonWebKey ecKey=keys.get(0);
compactProducer.signWith(new EcDsaJwsSignatureProvider(JwkUtils.toECPrivateKey(ecKey),SignatureAlgorithm.ES512));
assertEquals(compactProducer.getUnsignedEncodedJws(),ECSDA_SIGNATURE_PROTECTED_HEADER + "." + ENCODED_PAYLOAD);
assertEquals(132,Base64UrlUtility.decode(compactProducer.getEncodedSignature()).length);
JwsCompactConsumer compactConsumer=new JwsCompactConsumer(compactProducer.getSignedEncodedJws());
JsonWebKeys publicJwks=readKeySet("cookbookPublicSet.txt");
List publicKeys=publicJwks.getKeys();
JsonWebKey ecPublicKey=publicKeys.get(0);
assertTrue(compactConsumer.verifySignatureWith(ecPublicKey,SignatureAlgorithm.ES512));
}
finally {
Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testProtectingContentOnlySignature() throws Exception {
JwsJsonProducer jsonProducer=new JwsJsonProducer(PAYLOAD);
assertEquals(jsonProducer.getPlainPayload(),PAYLOAD);
assertEquals(jsonProducer.getUnsignedEncodedPayload(),ENCODED_PAYLOAD);
JwsHeaders unprotectedHeader=new JwsHeaders();
unprotectedHeader.setSignatureAlgorithm(SignatureAlgorithm.HS256);
unprotectedHeader.setKeyId(HMAC_KID_VALUE);
JsonWebKeys jwks=readKeySet("cookbookSecretSet.txt");
List keys=jwks.getKeys();
JsonWebKey key=keys.get(0);
jsonProducer.signWith(JwsUtils.getSignatureProvider(key,SignatureAlgorithm.HS256),null,unprotectedHeader);
assertEquals(jsonProducer.getJwsJsonSignedDocument(),PROTECTING_CONTENT_ONLY_JSON_GENERAL_SERIALIZATION);
JwsJsonConsumer jsonConsumer=new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument());
assertTrue(jsonConsumer.verifySignatureWith(key,SignatureAlgorithm.HS256));
jsonProducer=new JwsJsonProducer(PAYLOAD,true);
jsonProducer.signWith(JwsUtils.getSignatureProvider(key,SignatureAlgorithm.HS256),null,unprotectedHeader);
assertEquals(jsonProducer.getJwsJsonSignedDocument(),PROTECTING_CONTENT_ONLY_JSON_FLATTENED_SERIALIZATION);
jsonConsumer=new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument());
assertTrue(jsonConsumer.verifySignatureWith(key,SignatureAlgorithm.HS256));
}
Class: org.apache.cxf.rs.security.jose.jwe.JweCompactReaderWriterTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testEncryptDecryptAesWrapA128CBCHS256() throws Exception {
final String specPlainText="Live long and prosper.";
byte[] cekEncryptionKey=Base64UrlUtility.decode(KEY_ENCRYPTION_KEY_A3);
AesWrapKeyEncryptionAlgorithm keyEncryption=new AesWrapKeyEncryptionAlgorithm(cekEncryptionKey,KeyAlgorithm.A128KW);
JweEncryptionProvider encryption=new AesCbcHmacJweEncryption(ContentAlgorithm.A128CBC_HS256,CONTENT_ENCRYPTION_KEY_A3,INIT_VECTOR_A3,keyEncryption);
String jweContent=encryption.encrypt(specPlainText.getBytes(StandardCharsets.UTF_8),null);
assertEquals(JWE_OUTPUT_A3,jweContent);
AesWrapKeyDecryptionAlgorithm keyDecryption=new AesWrapKeyDecryptionAlgorithm(cekEncryptionKey);
JweDecryptionProvider decryption=new AesCbcHmacJweDecryption(keyDecryption);
String decryptedText=decryption.decrypt(jweContent).getContentText();
assertEquals(specPlainText,decryptedText);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testEncryptDecryptRSA15WrapA128CBCHS256() throws Exception {
final String specPlainText="Live long and prosper.";
RSAPublicKey publicKey=CryptoUtils.getRSAPublicKey(RSA_MODULUS_ENCODED_A1,RSA_PUBLIC_EXPONENT_ENCODED_A1);
KeyEncryptionProvider keyEncryption=new RSAKeyEncryptionAlgorithm(publicKey,KeyAlgorithm.RSA1_5);
JweEncryptionProvider encryption=new AesCbcHmacJweEncryption(ContentAlgorithm.A128CBC_HS256,CONTENT_ENCRYPTION_KEY_A3,INIT_VECTOR_A3,keyEncryption);
String jweContent=encryption.encrypt(specPlainText.getBytes(StandardCharsets.UTF_8),null);
RSAPrivateKey privateKey=CryptoUtils.getRSAPrivateKey(RSA_MODULUS_ENCODED_A1,RSA_PRIVATE_EXPONENT_ENCODED_A1);
KeyDecryptionProvider keyDecryption=new RSAKeyDecryptionAlgorithm(privateKey,KeyAlgorithm.RSA1_5);
JweDecryptionProvider decryption=new AesCbcHmacJweDecryption(keyDecryption);
String decryptedText=decryption.decrypt(jweContent).getContentText();
assertEquals(specPlainText,decryptedText);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testEncryptDecryptAesGcmWrapA128CBCHS256() throws Exception {
if ("IBM Corporation".equals(System.getProperty("java.vendor"))) {
return;
}
final String specPlainText="Live long and prosper.";
byte[] cekEncryptionKey=Base64UrlUtility.decode(KEY_ENCRYPTION_KEY_A3);
AesGcmWrapKeyEncryptionAlgorithm keyEncryption=new AesGcmWrapKeyEncryptionAlgorithm(cekEncryptionKey,KeyAlgorithm.A128GCMKW);
JweEncryptionProvider encryption=new AesCbcHmacJweEncryption(ContentAlgorithm.A128CBC_HS256,CONTENT_ENCRYPTION_KEY_A3,INIT_VECTOR_A3,keyEncryption);
String jweContent=encryption.encrypt(specPlainText.getBytes(StandardCharsets.UTF_8),null);
AesGcmWrapKeyDecryptionAlgorithm keyDecryption=new AesGcmWrapKeyDecryptionAlgorithm(cekEncryptionKey);
JweDecryptionProvider decryption=new AesCbcHmacJweDecryption(keyDecryption);
String decryptedText=decryption.decrypt(jweContent).getContentText();
assertEquals(specPlainText,decryptedText);
}
InternalCallVerifier EqualityVerifier
@Test public void testECDHESDirectKeyEncryption() throws Exception {
ECPrivateKey bobPrivateKey=CryptoUtils.getECPrivateKey(JsonWebKey.EC_CURVE_P256,"VEmDZpDXXK8p8N0Cndsxs924q6nS1RXFASRl6BfUqdw");
final ECPublicKey bobPublicKey=CryptoUtils.getECPublicKey(JsonWebKey.EC_CURVE_P256,"weNJy2HscCSM6AEDTDg04biOvhFhyyWvOHQfeF_PxMQ","e8lnCO-AlStT-NJVX-crhB7QRYhiix03illJOVAOyck");
JweEncryptionProvider jweOut=new EcdhDirectKeyJweEncryption(bobPublicKey,JsonWebKey.EC_CURVE_P256,"Alice","Bob",ContentAlgorithm.A128GCM);
String jweOutput=jweOut.encrypt("Hello".getBytes(),null);
JweDecryptionProvider jweIn=new EcdhDirectKeyJweDecryption(bobPrivateKey,ContentAlgorithm.A128GCM);
assertEquals("Hello",jweIn.decrypt(jweOutput).getContentText());
}
Class: org.apache.cxf.rs.security.jose.jwe.JweJsonConsumerTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testSingleRecipientAllTypeOfHeadersAndAad(){
final String text="The true sign of intelligence is not knowledge but imagination.";
SecretKey wrapperKey=CryptoUtils.createSecretKeySpec(JweJsonProducerTest.WRAPPER_BYTES1,"AES");
JweDecryptionProvider jwe=JweUtils.createJweDecryptionProvider(wrapperKey,KeyAlgorithm.A128KW,ContentAlgorithm.A128GCM);
JweJsonConsumer consumer=new JweJsonConsumer(JweJsonProducerTest.SINGLE_RECIPIENT_ALL_HEADERS_AAD_OUTPUT);
JweDecryptionOutput out=consumer.decryptWith(jwe);
assertEquals(text,out.getContentText());
assertEquals(JweJsonProducerTest.EXTRA_AAD_SOURCE,consumer.getAadText());
}
Class: org.apache.cxf.rs.security.jose.jwe.JweJsonProducerTest InternalCallVerifier EqualityVerifier
@Test public void testMultipleRecipients(){
final String text="The true sign of intelligence is not knowledge but imagination.";
SecretKey wrapperKey1=CryptoUtils.createSecretKeySpec(WRAPPER_BYTES1,"AES");
SecretKey wrapperKey2=CryptoUtils.createSecretKeySpec(WRAPPER_BYTES2,"AES");
JweHeaders protectedHeaders=new JweHeaders(ContentAlgorithm.A128GCM);
JweHeaders sharedUnprotectedHeaders=new JweHeaders();
sharedUnprotectedHeaders.setJsonWebKeysUrl("https://server.example.com/keys.jwks");
sharedUnprotectedHeaders.setKeyEncryptionAlgorithm(KeyAlgorithm.A128KW);
List jweList=new LinkedList();
KeyEncryptionProvider keyEncryption1=JweUtils.getSecretKeyEncryptionAlgorithm(wrapperKey1,KeyAlgorithm.A128KW);
ContentEncryptionProvider contentEncryption=JweUtils.getContentEncryptionProvider(ContentAlgorithm.A128GCM);
JweEncryptionProvider jwe1=new JweEncryption(keyEncryption1,contentEncryption);
KeyEncryptionProvider keyEncryption2=JweUtils.getSecretKeyEncryptionAlgorithm(wrapperKey2,KeyAlgorithm.A128KW);
JweEncryptionProvider jwe2=new JweEncryption(keyEncryption2,contentEncryption);
jweList.add(jwe1);
jweList.add(jwe2);
JweJsonProducer p=new JweJsonProducer(protectedHeaders,sharedUnprotectedHeaders,StringUtils.toBytesUTF8(text),StringUtils.toBytesUTF8(EXTRA_AAD_SOURCE),false){
protected JweEncryptionInput createEncryptionInput( JweHeaders jsonHeaders){
JweEncryptionInput input=super.createEncryptionInput(jsonHeaders);
input.setCek(CEK_BYTES);
input.setIv(JweCompactReaderWriterTest.INIT_VECTOR_A1);
return input;
}
}
;
String jweJson=p.encryptWith(jweList);
assertEquals(MULTIPLE_RECIPIENTS_OUTPUT,jweJson);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testSingleRecipientAllTypeOfHeadersAndAad(){
final String text="The true sign of intelligence is not knowledge but imagination.";
SecretKey wrapperKey=CryptoUtils.createSecretKeySpec(WRAPPER_BYTES1,"AES");
JweHeaders protectedHeaders=new JweHeaders(ContentAlgorithm.A128GCM);
JweHeaders sharedUnprotectedHeaders=new JweHeaders();
sharedUnprotectedHeaders.setJsonWebKeysUrl("https://server.example.com/keys.jwks");
JweEncryptionProvider jwe=JweUtils.createJweEncryptionProvider(wrapperKey,KeyAlgorithm.A128KW,ContentAlgorithm.A128GCM,null);
JweJsonProducer p=new JweJsonProducer(protectedHeaders,sharedUnprotectedHeaders,StringUtils.toBytesUTF8(text),StringUtils.toBytesUTF8(EXTRA_AAD_SOURCE),false){
protected JweEncryptionInput createEncryptionInput( JweHeaders jsonHeaders){
JweEncryptionInput input=super.createEncryptionInput(jsonHeaders);
input.setCek(CEK_BYTES);
input.setIv(JweCompactReaderWriterTest.INIT_VECTOR_A1);
return input;
}
}
;
JweHeaders recepientUnprotectedHeaders=new JweHeaders();
recepientUnprotectedHeaders.setKeyEncryptionAlgorithm(KeyAlgorithm.A128KW);
String jweJson=p.encryptWith(jwe,recepientUnprotectedHeaders);
assertEquals(SINGLE_RECIPIENT_ALL_HEADERS_AAD_OUTPUT,jweJson);
}
Class: org.apache.cxf.rs.security.jose.jwe.JwePbeHmacAesWrapTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testEncryptDecryptPbesHmacAesWrapA128CBCHS256() throws Exception {
final String specPlainText="Live long and prosper.";
final String password="Thus from my lips, by yours, my sin is purged.";
KeyEncryptionProvider keyEncryption=new PbesHmacAesWrapKeyEncryptionAlgorithm(password,KeyAlgorithm.PBES2_HS256_A128KW);
JweEncryptionProvider encryption=new AesCbcHmacJweEncryption(ContentAlgorithm.A128CBC_HS256,keyEncryption);
String jweContent=encryption.encrypt(specPlainText.getBytes(StandardCharsets.UTF_8),null);
PbesHmacAesWrapKeyDecryptionAlgorithm keyDecryption=new PbesHmacAesWrapKeyDecryptionAlgorithm(password);
JweDecryptionProvider decryption=new AesCbcHmacJweDecryption(keyDecryption);
String decryptedText=decryption.decrypt(jweContent).getContentText();
assertEquals(specPlainText,decryptedText);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testEncryptDecryptPbesHmacAesWrapAesGcm() throws Exception {
final String specPlainText="Live long and prosper.";
JweHeaders headers=new JweHeaders();
headers.setKeyEncryptionAlgorithm(KeyAlgorithm.PBES2_HS256_A128KW);
headers.setContentEncryptionAlgorithm(ContentAlgorithm.A128GCM);
final String password="Thus from my lips, by yours, my sin is purged.";
KeyEncryptionProvider keyEncryption=new PbesHmacAesWrapKeyEncryptionAlgorithm(password,KeyAlgorithm.PBES2_HS256_A128KW);
JweEncryptionProvider encryption=new JweEncryption(keyEncryption,new AesGcmContentEncryptionAlgorithm(ContentAlgorithm.A128GCM));
String jweContent=encryption.encrypt(specPlainText.getBytes(StandardCharsets.UTF_8),null);
PbesHmacAesWrapKeyDecryptionAlgorithm keyDecryption=new PbesHmacAesWrapKeyDecryptionAlgorithm(password);
JweDecryptionProvider decryption=new JweDecryption(keyDecryption,new AesGcmContentDecryptionAlgorithm(ContentAlgorithm.A128GCM));
String decryptedText=decryption.decrypt(jweContent).getContentText();
assertEquals(specPlainText,decryptedText);
}
Class: org.apache.cxf.rs.security.jose.jwk.JsonWebKeyTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testEncryptDecryptPrivateSet() throws Exception {
final String password="Thus from my lips, by yours, my sin is purged.";
Security.addProvider(new BouncyCastleProvider());
try {
JsonWebKeys jwks=readKeySet("jwkPrivateSet.txt");
validatePrivateSet(jwks);
String encryptedKeySet=JwkUtils.encryptJwkSet(jwks,password.toCharArray());
JweCompactConsumer c=new JweCompactConsumer(encryptedKeySet);
assertEquals("jwk-set+json",c.getJweHeaders().getContentType());
assertEquals(KeyAlgorithm.PBES2_HS256_A128KW,c.getJweHeaders().getKeyEncryptionAlgorithm());
assertEquals(ContentAlgorithm.A128CBC_HS256,c.getJweHeaders().getContentEncryptionAlgorithm());
assertNotNull(c.getJweHeaders().getHeader("p2s"));
assertNotNull(c.getJweHeaders().getHeader("p2c"));
jwks=JwkUtils.decryptJwkSet(encryptedKeySet,password.toCharArray());
validatePrivateSet(jwks);
}
finally {
Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testPublicSetAsList() throws Exception {
JsonWebKeys jwks=readKeySet("jwkPublicSet.txt");
List keys=jwks.getKeys();
assertEquals(3,keys.size());
JsonWebKey ecKey=keys.get(0);
assertEquals(6,ecKey.asMap().size());
validatePublicEcKey(ecKey);
JsonWebKey rsaKey=keys.get(1);
assertEquals(5,rsaKey.asMap().size());
validatePublicRsaKey(rsaKey);
JsonWebKey rsaKeyCert=keys.get(2);
assertEquals(3,rsaKeyCert.asMap().size());
assertEquals(3,rsaKeyCert.getX509Chain().size());
List certs=JwkUtils.toX509CertificateChain(rsaKeyCert);
assertEquals(3,certs.size());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testPublicSetAsMap() throws Exception {
JsonWebKeys jwks=readKeySet("jwkPublicSet.txt");
Map keysMap=jwks.getKeyIdMap();
assertEquals(3,keysMap.size());
JsonWebKey rsaKey=keysMap.get(RSA_KID_VALUE);
assertEquals(5,rsaKey.asMap().size());
validatePublicRsaKey(rsaKey);
JsonWebKey ecKey=keysMap.get(EC_KID_VALUE);
assertEquals(6,ecKey.asMap().size());
validatePublicEcKey(ecKey);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testSecretSetAsList() throws Exception {
JsonWebKeys jwks=readKeySet("jwkSecretSet.txt");
List keys=jwks.getKeys();
assertEquals(2,keys.size());
JsonWebKey aesKey=keys.get(0);
assertEquals(4,aesKey.asMap().size());
validateSecretAesKey(aesKey);
JsonWebKey hmacKey=keys.get(1);
assertEquals(4,hmacKey.asMap().size());
validateSecretHmacKey(hmacKey);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testEncryptDecryptPrivateKey() throws Exception {
final String password="Thus from my lips, by yours, my sin is purged.";
final String key="{\"kty\":\"oct\"," + "\"alg\":\"A128KW\"," + "\"k\":\"GawgguFyGrWKav7AX4VKUg\","+ "\"kid\":\"AesWrapKey\"}";
Security.addProvider(new BouncyCastleProvider());
try {
JsonWebKey jwk=readKey(key);
validateSecretAesKey(jwk);
String encryptedKey=JwkUtils.encryptJwkKey(jwk,password.toCharArray());
JweCompactConsumer c=new JweCompactConsumer(encryptedKey);
assertEquals("jwk+json",c.getJweHeaders().getContentType());
assertEquals(KeyAlgorithm.PBES2_HS256_A128KW,c.getJweHeaders().getKeyEncryptionAlgorithm());
assertEquals(ContentAlgorithm.A128CBC_HS256,c.getJweHeaders().getContentEncryptionAlgorithm());
assertNotNull(c.getJweHeaders().getHeader("p2s"));
assertNotNull(c.getJweHeaders().getHeader("p2c"));
jwk=JwkUtils.decryptJwkKey(encryptedKey,password.toCharArray());
validateSecretAesKey(jwk);
}
finally {
Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
}
}
Class: org.apache.cxf.rs.security.jose.jws.JwsCompactHeaderTest BooleanVerifier InternalCallVerifier
@Test public void testCriticalHeader(){
String payload="this is a JWS with critical header";
String criticalParameter="criticalParameter";
String criticalParameter1="criticalParameter1";
String criticalParameter2="criticalParameter2";
String criticalParameter3="criticalParameter3";
String criticalValue="criticalValue";
String criticalValue1="criticalValue1";
String criticalValue2="criticalValue2";
String criticalValue3="criticalValue3";
JwsCompactProducer producer=new JwsCompactProducer(payload);
producer.getJwsHeaders().setSignatureAlgorithm(SignatureAlgorithm.HS512);
List criticalHeader=new ArrayList();
criticalHeader.add(criticalParameter1);
producer.getJwsHeaders().setCritical(criticalHeader);
producer.signWith(new HmacJwsSignatureProvider(ENCODED_MAC_KEY,SignatureAlgorithm.HS256));
String signedJws=producer.getSignedEncodedJws();
JwsCompactConsumer consumer=new JwsCompactConsumer(signedJws);
assertFalse(consumer.validateCriticalHeaders());
criticalHeader.add(criticalParameter2);
criticalHeader.add(criticalParameter3);
producer=new JwsCompactProducer(payload);
producer.getJwsHeaders().setSignatureAlgorithm(SignatureAlgorithm.HS512);
producer.getJwsHeaders().setCritical(criticalHeader);
producer.getJwsHeaders().setHeader(criticalParameter1,criticalValue1);
producer.getJwsHeaders().setHeader(criticalParameter2,criticalValue2);
producer.getJwsHeaders().setHeader(criticalParameter3,criticalValue3);
producer.signWith(new HmacJwsSignatureProvider(ENCODED_MAC_KEY,SignatureAlgorithm.HS256));
signedJws=producer.getSignedEncodedJws();
consumer=new JwsCompactConsumer(signedJws);
assertTrue(consumer.validateCriticalHeaders());
criticalHeader=new ArrayList();
criticalHeader.add(criticalParameter);
criticalHeader.add(criticalParameter);
producer=new JwsCompactProducer(payload);
producer.getJwsHeaders().setSignatureAlgorithm(SignatureAlgorithm.HS512);
producer.getJwsHeaders().setHeader(criticalParameter,criticalValue);
producer.getJwsHeaders().setCritical(criticalHeader);
producer.signWith(new HmacJwsSignatureProvider(ENCODED_MAC_KEY,SignatureAlgorithm.HS256));
signedJws=producer.getSignedEncodedJws();
consumer=new JwsCompactConsumer(signedJws);
assertFalse(consumer.validateCriticalHeaders());
}
BooleanVerifier InternalCallVerifier
@Test public void verifyJwsWithTwoAlgHeaderFieldsBogusFieldFirst() throws Exception {
JwsCompactConsumer jwsConsumer=new JwsCompactConsumer(TWO_ALG_HEADER_FIELDS_IN_JWS_BOGUS_FIRST);
boolean result=jwsConsumer.verifySignatureWith(new HmacJwsSignatureVerifier(ENCODED_MAC_KEY,SignatureAlgorithm.HS256));
assertFalse(result);
}
Class: org.apache.cxf.rs.security.jose.jws.JwsCompactReaderWriterTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testReadJwsWithJwkSignedByMac() throws Exception {
JwsJwtCompactConsumer jws=new JwsJwtCompactConsumer(ENCODED_TOKEN_WITH_JSON_KEY_SIGNED_BY_MAC);
assertTrue(jws.verifySignatureWith(new HmacJwsSignatureVerifier(ENCODED_MAC_KEY,SignatureAlgorithm.HS256)));
JwtToken token=jws.getJwtToken();
JwsHeaders headers=new JwsHeaders(token.getJwsHeaders());
assertEquals(JoseType.JWT,headers.getType());
assertEquals(SignatureAlgorithm.HS256,headers.getSignatureAlgorithm());
JsonWebKey key=headers.getJsonWebKey();
assertEquals(KeyType.OCTET,key.getKeyType());
List keyOps=key.getKeyOperation();
assertEquals(2,keyOps.size());
assertEquals(KeyOperation.SIGN,keyOps.get(0));
assertEquals(KeyOperation.VERIFY,keyOps.get(1));
validateSpecClaim(token.getClaims());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testJwsPsSha() throws Exception {
Security.addProvider(new BouncyCastleProvider());
try {
JwsHeaders outHeaders=new JwsHeaders();
outHeaders.setSignatureAlgorithm(SignatureAlgorithm.PS256);
JwsCompactProducer producer=initSpecJwtTokenWriter(outHeaders);
PrivateKey privateKey=CryptoUtils.getRSAPrivateKey(RSA_MODULUS_ENCODED,RSA_PRIVATE_EXPONENT_ENCODED);
String signed=producer.signWith(new PrivateKeyJwsSignatureProvider(privateKey,SignatureAlgorithm.PS256));
JwsJwtCompactConsumer jws=new JwsJwtCompactConsumer(signed);
RSAPublicKey key=CryptoUtils.getRSAPublicKey(RSA_MODULUS_ENCODED,RSA_PUBLIC_EXPONENT_ENCODED);
assertTrue(jws.verifySignatureWith(new PublicKeyJwsSignatureVerifier(key,SignatureAlgorithm.PS256)));
JwtToken token=jws.getJwtToken();
JwsHeaders inHeaders=new JwsHeaders(token.getJwsHeaders());
assertEquals(SignatureAlgorithm.PS256,inHeaders.getSignatureAlgorithm());
validateSpecClaim(token.getClaims());
}
finally {
Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
}
}
InternalCallVerifier EqualityVerifier
@Test public void testWriteReadJwsUnsigned() throws Exception {
JwsHeaders headers=new JwsHeaders(JoseType.JWT);
headers.setSignatureAlgorithm(SignatureAlgorithm.NONE);
JwtClaims claims=new JwtClaims();
claims.setIssuer("https://jwt-idp.example.com");
claims.setSubject("mailto:mike@example.com");
claims.setAudiences(Collections.singletonList("https://jwt-rp.example.net"));
claims.setNotBefore(1300815780L);
claims.setExpiryTime(1300819380L);
claims.setClaim("http://claims.example.com/member",true);
JwsCompactProducer writer=new JwsJwtCompactProducer(headers,claims);
String signed=writer.getSignedEncodedJws();
JwsJwtCompactConsumer reader=new JwsJwtCompactConsumer(signed);
assertEquals(0,reader.getDecodedSignature().length);
JwtToken token=reader.getJwtToken();
assertEquals(new JwtToken(headers,claims),token);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testReadJwsSignedByPrivateKey() throws Exception {
JwsJwtCompactConsumer jws=new JwsJwtCompactConsumer(ENCODED_TOKEN_SIGNED_BY_PRIVATE_KEY);
RSAPublicKey key=CryptoUtils.getRSAPublicKey(RSA_MODULUS_ENCODED,RSA_PUBLIC_EXPONENT_ENCODED);
assertTrue(jws.verifySignatureWith(new PublicKeyJwsSignatureVerifier(key,SignatureAlgorithm.RS256)));
JwtToken token=jws.getJwtToken();
JwsHeaders headers=new JwsHeaders(token.getJwsHeaders());
assertEquals(SignatureAlgorithm.RS256,headers.getSignatureAlgorithm());
validateSpecClaim(token.getClaims());
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testWriteReadJwsUnencodedPayload() throws Exception {
JwsHeaders headers=new JwsHeaders(SignatureAlgorithm.HS256);
headers.setPayloadEncodingStatus(false);
JwsCompactProducer producer=new JwsCompactProducer(headers,UNSIGNED_PLAIN_DOCUMENT,true);
producer.signWith(new HmacJwsSignatureProvider(ENCODED_MAC_KEY,SignatureAlgorithm.HS256));
assertEquals(TOKEN_WITH_DETACHED_UNENCODED_PAYLOAD,producer.getSignedEncodedJws());
JwsCompactConsumer consumer=new JwsCompactConsumer(TOKEN_WITH_DETACHED_UNENCODED_PAYLOAD,UNSIGNED_PLAIN_DOCUMENT);
assertTrue(consumer.verifySignatureWith(new HmacJwsSignatureVerifier(ENCODED_MAC_KEY,SignatureAlgorithm.HS256)));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testWriteReadJwsSignedByESPrivateKey() throws Exception {
JwsHeaders headers=new JwsHeaders();
headers.setSignatureAlgorithm(SignatureAlgorithm.ES256);
JwsCompactProducer jws=initSpecJwtTokenWriter(headers);
ECPrivateKey privateKey=CryptoUtils.getECPrivateKey(JsonWebKey.EC_CURVE_P256,EC_PRIVATE_KEY_ENCODED);
jws.signWith(new EcDsaJwsSignatureProvider(privateKey,SignatureAlgorithm.ES256));
String signedJws=jws.getSignedEncodedJws();
ECPublicKey publicKey=CryptoUtils.getECPublicKey(JsonWebKey.EC_CURVE_P256,EC_X_POINT_ENCODED,EC_Y_POINT_ENCODED);
JwsJwtCompactConsumer jwsConsumer=new JwsJwtCompactConsumer(signedJws);
assertTrue(jwsConsumer.verifySignatureWith(new EcDsaJwsSignatureVerifier(publicKey,SignatureAlgorithm.ES256)));
JwtToken token=jwsConsumer.getJwtToken();
JwsHeaders headersReceived=new JwsHeaders(token.getJwsHeaders());
assertEquals(SignatureAlgorithm.ES256,headersReceived.getSignatureAlgorithm());
validateSpecClaim(token.getClaims());
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testReadJwsSignedByMacSpecExample() throws Exception {
JwsJwtCompactConsumer jws=new JwsJwtCompactConsumer(ENCODED_TOKEN_SIGNED_BY_MAC);
assertTrue(jws.verifySignatureWith(new HmacJwsSignatureVerifier(ENCODED_MAC_KEY,SignatureAlgorithm.HS256)));
JwtToken token=jws.getJwtToken();
JwsHeaders headers=new JwsHeaders(token.getJwsHeaders());
assertEquals(JoseType.JWT,headers.getType());
assertEquals(SignatureAlgorithm.HS256,headers.getSignatureAlgorithm());
validateSpecClaim(token.getClaims());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testWriteJwsSignedByMacSpecExample() throws Exception {
JwsHeaders headers=new JwsHeaders();
headers.setType(JoseType.JWT);
headers.setSignatureAlgorithm(SignatureAlgorithm.HS256);
JwsCompactProducer jws=initSpecJwtTokenWriter(headers);
jws.signWith(new HmacJwsSignatureProvider(ENCODED_MAC_KEY,SignatureAlgorithm.HS256));
assertEquals(ENCODED_TOKEN_SIGNED_BY_MAC,jws.getSignedEncodedJws());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testWriteJwsSignedByPrivateKey() throws Exception {
JwsHeaders headers=new JwsHeaders();
headers.setSignatureAlgorithm(SignatureAlgorithm.RS256);
JwsCompactProducer jws=initSpecJwtTokenWriter(headers);
PrivateKey key=CryptoUtils.getRSAPrivateKey(RSA_MODULUS_ENCODED,RSA_PRIVATE_EXPONENT_ENCODED);
jws.signWith(new PrivateKeyJwsSignatureProvider(key,SignatureAlgorithm.RS256));
assertEquals(ENCODED_TOKEN_SIGNED_BY_PRIVATE_KEY,jws.getSignedEncodedJws());
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testNoneSignature() throws Exception {
JwtClaims claims=new JwtClaims();
claims.setClaim("a","b");
JwsJwtCompactProducer producer=new JwsJwtCompactProducer(claims);
producer.signWith(new NoneJwsSignatureProvider());
JwsJwtCompactConsumer consumer=new JwsJwtCompactConsumer(producer.getSignedEncodedJws());
assertTrue(consumer.verifySignatureWith(new NoneJwsSignatureVerifier()));
JwtClaims claims2=consumer.getJwtClaims();
assertEquals(claims,claims2);
}
Class: org.apache.cxf.rs.security.jose.jws.JwsJsonConsumerTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testVerifyDualSignedDocument() throws Exception {
JwsJsonConsumer consumer=new JwsJsonConsumer(DUAL_SIGNED_DOCUMENT);
JsonWebKeys jwks=readKeySet("jwkPublicJsonConsumerSet.txt");
List sigEntries=consumer.getSignatureEntries();
assertEquals(2,sigEntries.size());
String firstKid=(String)sigEntries.get(0).getKeyId();
assertEquals(KID_OF_THE_FIRST_SIGNER,firstKid);
JsonWebKey rsaKey=jwks.getKey(firstKid);
assertNotNull(rsaKey);
assertTrue(sigEntries.get(0).verifySignatureWith(rsaKey));
String secondKid=(String)sigEntries.get(1).getKeyId();
assertEquals(KID_OF_THE_SECOND_SIGNER,secondKid);
JsonWebKey ecKey=jwks.getKey(secondKid);
assertNotNull(ecKey);
assertTrue(sigEntries.get(1).verifySignatureWith(ecKey));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testVerifySignedWithProtectedHeaderOnlyUnencodedPayload(){
JwsJsonConsumer consumer=new JwsJsonConsumer(JwsJsonProducerTest.SIGNED_JWS_JSON_FLAT_UNENCODED_DOCUMENT);
assertEquals(JwsJsonProducerTest.UNSIGNED_PLAIN_DOCUMENT,consumer.getJwsPayload());
assertEquals(JwsJsonProducerTest.UNSIGNED_PLAIN_DOCUMENT,consumer.getDecodedJwsPayload());
assertTrue(consumer.verifySignatureWith(new HmacJwsSignatureVerifier(JwsJsonProducerTest.ENCODED_MAC_KEY_1,SignatureAlgorithm.HS256)));
}
Class: org.apache.cxf.rs.security.jose.jws.JwsJsonProducerTest InternalCallVerifier EqualityVerifier
@Test public void testDualSignWithProtectedHeaderOnly(){
JwsJsonProducer producer=new JwsJsonProducer(UNSIGNED_PLAIN_JSON_DOCUMENT);
JwsHeaders headerEntries=new JwsHeaders();
headerEntries.setSignatureAlgorithm(SignatureAlgorithm.HS256);
producer.signWith(new HmacJwsSignatureProvider(ENCODED_MAC_KEY_1,SignatureAlgorithm.HS256),headerEntries);
producer.signWith(new HmacJwsSignatureProvider(ENCODED_MAC_KEY_2,SignatureAlgorithm.HS256),headerEntries);
assertEquals(DUAL_SIGNED_JWS_JSON_DOCUMENT,producer.getJwsJsonSignedDocument());
}
InternalCallVerifier EqualityVerifier
@Test public void testSignWithProtectedHeaderOnlyFlat(){
JwsJsonProducer producer=new JwsJsonProducer(UNSIGNED_PLAIN_JSON_DOCUMENT,true);
JwsHeaders headerEntries=new JwsHeaders();
headerEntries.setSignatureAlgorithm(SignatureAlgorithm.HS256);
producer.signWith(new HmacJwsSignatureProvider(ENCODED_MAC_KEY_1,SignatureAlgorithm.HS256),headerEntries);
assertEquals(SIGNED_JWS_JSON_FLAT_DOCUMENT,producer.getJwsJsonSignedDocument());
}
InternalCallVerifier EqualityVerifier
@Test public void testSignWithProtectedHeaderOnly(){
JwsJsonProducer producer=new JwsJsonProducer(UNSIGNED_PLAIN_JSON_DOCUMENT);
JwsHeaders headerEntries=new JwsHeaders();
headerEntries.setSignatureAlgorithm(SignatureAlgorithm.HS256);
producer.signWith(new HmacJwsSignatureProvider(ENCODED_MAC_KEY_1,SignatureAlgorithm.HS256),headerEntries);
assertEquals(SIGNED_JWS_JSON_DOCUMENT,producer.getJwsJsonSignedDocument());
}
InternalCallVerifier EqualityVerifier
@Test public void testSignWithProtectedHeaderOnlyUnencodedPayload(){
JwsJsonProducer producer=new JwsJsonProducer(UNSIGNED_PLAIN_DOCUMENT,true);
JwsHeaders headers=new JwsHeaders();
headers.setSignatureAlgorithm(SignatureAlgorithm.HS256);
headers.setPayloadEncodingStatus(false);
producer.signWith(new HmacJwsSignatureProvider(ENCODED_MAC_KEY_1,SignatureAlgorithm.HS256),headers);
assertEquals(SIGNED_JWS_JSON_FLAT_UNENCODED_DOCUMENT,producer.getJwsJsonSignedDocument());
}
Class: org.apache.cxf.rs.security.jose.jws.JwsUtilsTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testLoadVerificationKeys() throws Exception {
Properties p=new Properties();
p.put(JoseConstants.RSSEC_KEY_STORE_FILE,"org/apache/cxf/rs/security/jose/jws/alice.jks");
p.put(JoseConstants.RSSEC_KEY_STORE_PSWD,"password");
p.put(JoseConstants.RSSEC_KEY_STORE_ALIAS,"alice");
JsonWebKeys keySet=JwsUtils.loadPublicVerificationKeys(createMessage(),p);
assertEquals(1,keySet.asMap().size());
List keys=keySet.getRsaKeys();
assertEquals(1,keys.size());
JsonWebKey key=keys.get(0);
assertEquals(KeyType.RSA,key.getKeyType());
assertEquals("alice",key.getKeyId());
assertNotNull(key.getKeyProperty(JsonWebKey.RSA_PUBLIC_EXP));
assertNotNull(key.getKeyProperty(JsonWebKey.RSA_MODULUS));
assertNull(key.getKeyProperty(JsonWebKey.RSA_PRIVATE_EXP));
}
Class: org.apache.cxf.rs.security.oauth2.grants.TokenGrantHandlerTest BooleanVerifier InternalCallVerifier
@Test public void testComplexGrantSupported(){
ComplexGrantHandler handler=new ComplexGrantHandler(Arrays.asList("a","b"));
handler.setDataProvider(new OAuthDataProviderImpl());
ServerAccessToken t=handler.createAccessToken(createClient("a"),createMap("a"));
assertTrue(t instanceof BearerAccessToken);
}
BooleanVerifier InternalCallVerifier
@Test public void testSimpleGrantSupported(){
SimpleGrantHandler handler=new SimpleGrantHandler();
handler.setDataProvider(new OAuthDataProviderImpl());
ServerAccessToken t=handler.createAccessToken(createClient("a"),createMap("a"));
assertTrue(t instanceof BearerAccessToken);
}
Class: org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProviderTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test @SuppressWarnings({"unchecked","rawtypes"}) public void testReadTokenIntrospection() throws Exception {
String response="{\"active\":true,\"client_id\":\"WjcK94pnec7CyA\",\"username\":\"alice\",\"token_type\":\"Bearer\"" + ",\"scope\":\"a\",\"aud\":\"https://localhost:8082/service\"," + "\"iat\":1453472181,\"exp\":1453475781}";
OAuthJSONProvider provider=new OAuthJSONProvider();
TokenIntrospection t=(TokenIntrospection)provider.readFrom((Class)TokenIntrospection.class,TokenIntrospection.class,new Annotation[]{},MediaType.APPLICATION_JSON_TYPE,new MetadataMap(),new ByteArrayInputStream(response.getBytes()));
assertTrue(t.isActive());
assertEquals("WjcK94pnec7CyA",t.getClientId());
assertEquals("alice",t.getUsername());
assertEquals("a",t.getScope());
assertEquals(1,t.getAud().size());
assertEquals("https://localhost:8082/service",t.getAud().get(0));
assertEquals(1453472181L,t.getIat().longValue());
assertEquals(1453475781L,t.getExp().longValue());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test @SuppressWarnings({"unchecked","rawtypes"}) public void testReadTokenIntrospectionMultipleAuds() throws Exception {
String response="{\"active\":true,\"client_id\":\"WjcK94pnec7CyA\",\"username\":\"alice\",\"token_type\":\"Bearer\"" + ",\"scope\":\"a\",\"aud\":[\"https://localhost:8082/service\",\"https://localhost:8083/service\"]," + "\"iat\":1453472181,\"exp\":1453475781}";
OAuthJSONProvider provider=new OAuthJSONProvider();
TokenIntrospection t=(TokenIntrospection)provider.readFrom((Class)TokenIntrospection.class,TokenIntrospection.class,new Annotation[]{},MediaType.APPLICATION_JSON_TYPE,new MetadataMap(),new ByteArrayInputStream(response.getBytes()));
assertTrue(t.isActive());
assertEquals("WjcK94pnec7CyA",t.getClientId());
assertEquals("alice",t.getUsername());
assertEquals("a",t.getScope());
assertEquals(2,t.getAud().size());
assertEquals("https://localhost:8082/service",t.getAud().get(0));
assertEquals("https://localhost:8083/service",t.getAud().get(1));
assertEquals(1453472181L,t.getIat().longValue());
assertEquals(1453475781L,t.getExp().longValue());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test @SuppressWarnings({"unchecked","rawtypes"}) public void testReadTokenIntrospectionSingleAudAsArray() throws Exception {
String response="{\"active\":false,\"client_id\":\"WjcK94pnec7CyA\",\"username\":\"alice\",\"token_type\":\"Bearer\"" + ",\"scope\":\"a\",\"aud\":[\"https://localhost:8082/service\"]," + "\"iat\":1453472181,\"exp\":1453475781}";
OAuthJSONProvider provider=new OAuthJSONProvider();
TokenIntrospection t=(TokenIntrospection)provider.readFrom((Class)TokenIntrospection.class,TokenIntrospection.class,new Annotation[]{},MediaType.APPLICATION_JSON_TYPE,new MetadataMap(),new ByteArrayInputStream(response.getBytes()));
assertFalse(t.isActive());
assertEquals("WjcK94pnec7CyA",t.getClientId());
assertEquals("alice",t.getUsername());
assertEquals("a",t.getScope());
assertEquals(1,t.getAud().size());
assertEquals("https://localhost:8082/service",t.getAud().get(0));
assertEquals(1453472181L,t.getIat().longValue());
assertEquals(1453475781L,t.getExp().longValue());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testReadHawkClientAccessToken() throws Exception {
String response="{" + "\"access_token\":\"1234\"," + "\"token_type\":\"hawk\","+ "\"refresh_token\":\"5678\","+ "\"expires_in\":12345,"+ "\"scope\":\"read\","+ "\"secret\":\"adijq39jdlaska9asud\","+ "\"algorithm\":\"hmac-sha-256\","+ "\"my_parameter\":\"http://abc\""+ "}";
ClientAccessToken macToken=doReadClientAccessToken(response,"hawk",null);
assertEquals("adijq39jdlaska9asud",macToken.getParameters().get(OAuthConstants.HAWK_TOKEN_KEY));
assertEquals("hmac-sha-256",macToken.getParameters().get(OAuthConstants.HAWK_TOKEN_ALGORITHM));
}
Class: org.apache.cxf.rs.security.oauth2.tokens.hawk.HawkAccessTokenValidatorTest APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testValidateAccessToken() throws Exception {
HawkAccessToken macAccessToken=new HawkAccessToken(new Client("testClientId","testClientSecret",true),HmacAlgorithm.HmacSHA256,-1);
HttpServletRequest httpRequest=mockHttpRequest();
UriInfo uriInfo=mockUriInfo();
EasyMock.expect(dataProvider.getAccessToken(macAccessToken.getTokenKey())).andReturn(macAccessToken);
EasyMock.expect(messageContext.getHttpServletRequest()).andReturn(httpRequest);
EasyMock.expect(messageContext.getUriInfo()).andReturn(uriInfo);
EasyMock.replay(dataProvider,messageContext,httpRequest,uriInfo);
String authData=getClientAuthHeader(macAccessToken);
AccessTokenValidation tokenValidation=validator.validateAccessToken(messageContext,OAuthConstants.HAWK_AUTHORIZATION_SCHEME,authData.split(" ")[1],null);
assertNotNull(tokenValidation);
EasyMock.verify(dataProvider,messageContext,httpRequest);
}
Class: org.apache.cxf.rs.security.oauth2.utils.AuthorizationUtilsTest UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testThrowAuthorizationFailureSingleChallenge(){
try {
AuthorizationUtils.throwAuthorizationFailure(Collections.singleton("Basic"));
fail("WebApplicationException expected");
}
catch ( WebApplicationException ex) {
Response r=ex.getResponse();
assertEquals(401,r.getStatus());
Object value=r.getMetadata().getFirst(HttpHeaders.WWW_AUTHENTICATE);
assertNotNull(value);
assertEquals("Basic",value.toString());
}
}
UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testThrowAuthorizationFailureNoChallenge(){
try {
AuthorizationUtils.throwAuthorizationFailure(Collections.emptySet());
fail("WebApplicationException expected");
}
catch ( WebApplicationException ex) {
Response r=ex.getResponse();
assertEquals(401,r.getStatus());
Object value=r.getMetadata().getFirst(HttpHeaders.WWW_AUTHENTICATE);
assertNull(value);
}
}
UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testThrowAuthorizationFailureManyChallenges(){
Set challenges=new LinkedHashSet();
challenges.add("Basic");
challenges.add("Bearer");
try {
AuthorizationUtils.throwAuthorizationFailure(challenges);
fail("WebApplicationException expected");
}
catch ( WebApplicationException ex) {
Response r=ex.getResponse();
assertEquals(401,r.getStatus());
Object value=r.getMetadata().getFirst(HttpHeaders.WWW_AUTHENTICATE);
assertNotNull(value);
assertEquals("Basic,Bearer",value.toString());
}
}
Class: org.apache.cxf.rs.security.oauth2.utils.crypto.CryptoUtilsTest InternalCallVerifier EqualityVerifier
@Test public void testEncryptDecryptCodeGrant() throws Exception {
AuthorizationCodeRegistration codeReg=new AuthorizationCodeRegistration();
codeReg.setAudience("http://bar");
codeReg.setClient(p.getClient("1"));
ServerAuthorizationCodeGrant grant=p.createCodeGrant(codeReg);
ServerAuthorizationCodeGrant grant2=p.removeCodeGrant(grant.getCode());
assertEquals("http://bar",grant2.getAudience());
assertEquals("1",grant2.getClient().getClientId());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier PublicFieldVerifier HybridVerifier
@Test public void testClientJSON() throws Exception {
Client c=new Client("client","secret",true);
c.setSubject(new UserSubject("subject","id"));
JSONProvider jsonp=new JSONProvider();
jsonp.setMarshallAsJaxbElement(true);
jsonp.setUnmarshallAsJaxbElement(true);
ByteArrayOutputStream bos=new ByteArrayOutputStream();
jsonp.writeTo(c,Client.class,new Annotation[]{},MediaType.APPLICATION_JSON_TYPE,new MetadataMap(),bos);
String encrypted=CryptoUtils.encryptSequence(bos.toString(),p.key);
String decrypted=CryptoUtils.decryptSequence(encrypted,p.key);
Client c2=jsonp.readFrom(Client.class,Client.class,new Annotation[]{},MediaType.APPLICATION_JSON_TYPE,new MetadataMap(),new ByteArrayInputStream(decrypted.getBytes()));
assertEquals(c.getClientId(),c2.getClientId());
assertEquals(c.getClientSecret(),c2.getClientSecret());
assertTrue(c2.isConfidential());
assertEquals("subject",c2.getSubject().getLogin());
assertEquals("id",c2.getSubject().getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier PublicFieldVerifier
@Test public void testCodeGrantJSON() throws Exception {
Client c=new Client("client","secret",true);
ServerAuthorizationCodeGrant grant=new ServerAuthorizationCodeGrant(c,"code",1,2);
JSONProvider jsonp=new JSONProvider();
jsonp.setMarshallAsJaxbElement(true);
jsonp.setUnmarshallAsJaxbElement(true);
ByteArrayOutputStream bos=new ByteArrayOutputStream();
jsonp.writeTo(grant,ServerAuthorizationCodeGrant.class,new Annotation[]{},MediaType.APPLICATION_JSON_TYPE,new MetadataMap(),bos);
String encrypted=CryptoUtils.encryptSequence(bos.toString(),p.key);
String decrypted=CryptoUtils.decryptSequence(encrypted,p.key);
ServerAuthorizationCodeGrant grant2=jsonp.readFrom(ServerAuthorizationCodeGrant.class,Client.class,new Annotation[]{},MediaType.APPLICATION_JSON_TYPE,new MetadataMap(),new ByteArrayInputStream(decrypted.getBytes()));
assertEquals("code",grant2.getCode());
assertEquals(1,grant2.getExpiresIn());
assertEquals(2,grant2.getIssuedAt());
}
Class: org.apache.cxf.rs.security.saml.DeflateEncoderDecoderTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testInflateDeflate() throws Exception {
DeflateEncoderDecoder inflater=new DeflateEncoderDecoder();
byte[] deflated=inflater.deflateToken("valid_grant".getBytes());
InputStream is=inflater.inflateToken(deflated);
assertNotNull(is);
assertEquals("valid_grant",IOUtils.readStringFromStream(is));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testInflateDeflateWithTokenDuplication() throws Exception {
String token="valid_grant valid_grant valid_grant valid_grant valid_grant valid_grant";
DeflateEncoderDecoder deflateEncoderDecoder=new DeflateEncoderDecoder();
byte[] deflatedToken=deflateEncoderDecoder.deflateToken(token.getBytes());
String cxfInflatedToken=IOUtils.toString(deflateEncoderDecoder.inflateToken(deflatedToken));
String streamInflatedToken=IOUtils.toString(new InflaterInputStream(new ByteArrayInputStream(deflatedToken),new Inflater(true)));
assertEquals(streamInflatedToken,token);
assertEquals(cxfInflatedToken,token);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testInflateDeflateBase64() throws Exception {
DeflateEncoderDecoder inflater=new DeflateEncoderDecoder();
byte[] deflated=inflater.deflateToken("valid_grant".getBytes());
String base64String=Base64Utility.encode(deflated);
byte[] base64decoded=Base64Utility.decode(base64String);
InputStream is=inflater.inflateToken(base64decoded);
assertNotNull(is);
assertEquals("valid_grant",IOUtils.readStringFromStream(is));
}
Class: org.apache.cxf.rs.security.saml.sso.EHCacheUtilTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCreateCacheManager(){
Configuration conf=ConfigurationFactory.parseConfiguration(EHCacheUtil.class.getResource("/cxf-test-ehcache.xml"));
assertNotNull(conf);
conf.setName("testCache");
CacheManager manager1=EHCacheUtil.createCacheManager(conf);
assertNotNull(manager1);
CacheManager manager2=EHCacheUtil.createCacheManager();
assertNotNull(manager2);
manager1.shutdown();
assertEquals(Status.STATUS_SHUTDOWN,manager1.getStatus());
assertEquals(Status.STATUS_ALIVE,manager2.getStatus());
manager2.shutdown();
assertEquals(Status.STATUS_SHUTDOWN,manager2.getStatus());
}
Class: org.apache.cxf.rt.security.claims.ClaimTest InternalCallVerifier EqualityVerifier
@Test public void testCloneAllEquals(){
Claim claim=new Claim();
claim.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role"));
claim.setOptional(true);
claim.addValue("value1");
claim.addValue("value2");
claim.addValue("value3");
Claim clone=claim.clone();
assertEquals(claim,clone);
assertEquals(claim,new Claim(clone));
}
InternalCallVerifier EqualityVerifier
@Test public void testCloneValuesOnlySetEquals(){
Claim claim=new Claim();
claim.addValue("value1");
claim.addValue("value2");
Claim clone=claim.clone();
assertEquals(claim,clone);
assertEquals(claim,new Claim(clone));
}
InternalCallVerifier EqualityVerifier
@Test public void testCloneAndModifyValuesNotEquals(){
Claim claim=new Claim();
claim.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role"));
claim.setOptional(true);
claim.addValue("value1");
claim.addValue("value2");
claim.addValue("value3");
Claim clone=claim.clone();
claim.getValues().clear();
claim.addValue("value4");
assertNotEquals(claim,clone);
assertEquals(1,claim.getValues().size());
assertEquals(3,clone.getValues().size());
assertEquals(claim.getClaimType(),clone.getClaimType());
assertEquals(claim.isOptional(),clone.isOptional());
assertNotEquals(claim.getValues(),clone.getValues());
}
InternalCallVerifier EqualityVerifier
@Test public void testCloneAndModifyTypeNotEquals(){
Claim claim=new Claim();
claim.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role"));
claim.setOptional(true);
claim.addValue("value1");
claim.addValue("value2");
claim.addValue("value3");
Claim clone=claim.clone();
clone.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/value"));
assertNotEquals(claim,clone);
assertNotEquals(claim.getClaimType(),clone.getClaimType());
assertEquals(claim.isOptional(),clone.isOptional());
assertEquals(claim.getValues(),clone.getValues());
}
InternalCallVerifier EqualityVerifier
@Test public void testCloneUnset(){
Claim claim=new Claim();
Claim clone=claim.clone();
assertEquals(claim,clone);
assertEquals(claim,new Claim(clone));
}
InternalCallVerifier EqualityVerifier
@Test public void testCloneTypeOnlySetEquals(){
Claim claim=new Claim();
claim.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role"));
Claim clone=claim.clone();
assertEquals(claim,clone);
assertEquals(claim,new Claim(clone));
}
Class: org.apache.cxf.service.factory.ClientFactoryBeanTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testClientFactoryBean() throws Exception {
ClientFactoryBean cfBean=new ClientFactoryBean();
cfBean.setAddress("http://localhost/Hello");
cfBean.setBus(getBus());
cfBean.setServiceClass(HelloService.class);
Client client=cfBean.create();
assertNotNull(client);
Service service=client.getEndpoint().getService();
Map eps=service.getEndpoints();
assertEquals(1,eps.size());
Endpoint ep=eps.values().iterator().next();
EndpointInfo endpointInfo=ep.getEndpointInfo();
BindingInfo b=endpointInfo.getService().getBindings().iterator().next();
assertTrue(b instanceof SoapBindingInfo);
SoapBindingInfo sb=(SoapBindingInfo)b;
assertEquals("HelloServiceSoapBinding",b.getName().getLocalPart());
assertEquals("document",sb.getStyle());
assertEquals(4,b.getOperations().size());
BindingOperationInfo bop=b.getOperations().iterator().next();
SoapOperationInfo sop=bop.getExtensor(SoapOperationInfo.class);
assertNotNull(sop);
assertEquals("",sop.getAction());
assertEquals("document",sop.getStyle());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testJaxbExtraClass() throws Exception {
ClientFactoryBean cfBean=new ClientFactoryBean();
cfBean.setAddress("http://localhost/Hello");
cfBean.setBus(getBus());
cfBean.setServiceClass(HelloService.class);
Map props=cfBean.getProperties();
if (props == null) {
props=new HashMap();
}
props.put("jaxb.additionalContextClasses",new Class[]{GreetMe.class,GreetMeOneWay.class});
cfBean.setProperties(props);
Client client=cfBean.create();
assertNotNull(client);
Class>[] extraClass=((JAXBDataBinding)cfBean.getServiceFactory().getDataBinding()).getExtraClass();
assertEquals(extraClass.length,2);
assertEquals(extraClass[0],GreetMe.class);
assertEquals(extraClass[1],GreetMeOneWay.class);
}
Class: org.apache.cxf.service.factory.ReflectionServiceFactoryTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testUnwrappedBuild() throws Exception {
Service service=createService(false);
ServiceInfo si=service.getServiceInfos().get(0);
InterfaceInfo intf=si.getInterface();
assertEquals(4,intf.getOperations().size());
String ns=si.getName().getNamespaceURI();
OperationInfo sayHelloOp=intf.getOperation(new QName(ns,"sayHello"));
assertNotNull(sayHelloOp);
assertEquals("sayHello",sayHelloOp.getInput().getName().getLocalPart());
List messageParts=sayHelloOp.getInput().getMessageParts();
assertEquals(0,messageParts.size());
messageParts=sayHelloOp.getOutput().getMessageParts();
assertEquals(1,messageParts.size());
assertEquals("sayHelloResponse",sayHelloOp.getOutput().getName().getLocalPart());
MessagePartInfo mpi=messageParts.get(0);
assertEquals("return",mpi.getName().getLocalPart());
assertEquals(String.class,mpi.getTypeClass());
OperationInfo op=si.getInterface().getOperation(new QName(ns,"echoWithExchange"));
assertEquals(1,op.getInput().getMessageParts().size());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testServerFactoryBean() throws Exception {
Service service=createService(true);
assertEquals("test",service.get("test"));
ServerFactoryBean svrBean=new ServerFactoryBean();
svrBean.setAddress("http://localhost/Hello");
svrBean.setServiceFactory(serviceFactory);
svrBean.setServiceBean(new HelloServiceImpl());
svrBean.setBus(getBus());
Map props=new HashMap();
props.put("test","test");
serviceFactory.setProperties(props);
svrBean.setProperties(props);
Server server=svrBean.create();
assertNotNull(server);
Map eps=service.getEndpoints();
assertEquals(1,eps.size());
Endpoint ep=eps.values().iterator().next();
EndpointInfo endpointInfo=ep.getEndpointInfo();
assertEquals("test",ep.get("test"));
BindingInfo b=endpointInfo.getService().getBindings().iterator().next();
assertTrue(b instanceof SoapBindingInfo);
SoapBindingInfo sb=(SoapBindingInfo)b;
assertEquals("HelloServiceSoapBinding",b.getName().getLocalPart());
assertEquals("document",sb.getStyle());
assertEquals(4,b.getOperations().size());
BindingOperationInfo bop=b.getOperations().iterator().next();
SoapOperationInfo sop=bop.getExtensor(SoapOperationInfo.class);
assertNotNull(sop);
assertEquals("",sop.getAction());
assertEquals("document",sop.getStyle());
}
APIUtilityVerifier InternalCallVerifier NullVerifier ExceptionVerifier HybridVerifier
@Test(expected=ServiceConstructionException.class) public void testDocLiteralPartWithType() throws Exception {
serviceFactory=new ReflectionServiceFactoryBean();
serviceFactory.setBus(getBus());
serviceFactory.setServiceClass(NoBodyPartsImpl.class);
serviceFactory.getServiceConfigurations().add(0,new AbstractServiceConfiguration(){
@Override public Boolean isWrapped(){
return Boolean.FALSE;
}
@Override public Boolean isWrapped( Method m){
return Boolean.FALSE;
}
}
);
Service service=serviceFactory.create();
ServiceInfo serviceInfo=service.getServiceInfos().get(0);
QName qname=new QName("urn:org:apache:cxf:no_body_parts/wsdl","operation1");
MessageInfo mi=serviceInfo.getMessage(qname);
qname=new QName("urn:org:apache:cxf:no_body_parts/wsdl","mimeAttachment");
MessagePartInfo mpi=mi.getMessagePart(qname);
QName elementQName=mpi.getElementQName();
XmlSchemaElement element=serviceInfo.getXmlSchemaCollection().getElementByQName(elementQName);
assertNotNull(element);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testWrappedBuild() throws Exception {
Service service=createService(true);
ServiceInfo si=service.getServiceInfos().get(0);
InterfaceInfo intf=si.getInterface();
assertEquals(4,intf.getOperations().size());
String ns=si.getName().getNamespaceURI();
OperationInfo sayHelloOp=intf.getOperation(new QName(ns,"sayHello"));
assertNotNull(sayHelloOp);
assertEquals("sayHello",sayHelloOp.getInput().getName().getLocalPart());
List messageParts=sayHelloOp.getInput().getMessageParts();
assertEquals(1,messageParts.size());
assertNotNull(messageParts.get(0).getXmlSchema());
assertTrue(sayHelloOp.isUnwrappedCapable());
OperationInfo unwrappedOp=sayHelloOp.getUnwrappedOperation();
assertEquals("sayHello",unwrappedOp.getInput().getName().getLocalPart());
messageParts=unwrappedOp.getInput().getMessageParts();
assertEquals(0,messageParts.size());
messageParts=sayHelloOp.getOutput().getMessageParts();
assertEquals(1,messageParts.size());
assertEquals("sayHelloResponse",sayHelloOp.getOutput().getName().getLocalPart());
messageParts=unwrappedOp.getOutput().getMessageParts();
assertEquals("sayHelloResponse",unwrappedOp.getOutput().getName().getLocalPart());
assertEquals(1,messageParts.size());
MessagePartInfo mpi=messageParts.get(0);
assertEquals("return",mpi.getName().getLocalPart());
assertEquals(String.class,mpi.getTypeClass());
}
Class: org.apache.cxf.service.factory.RountripTest InternalCallVerifier EqualityVerifier
@Test public void testServerFactoryBean() throws Exception {
ServerFactoryBean svrBean=new ServerFactoryBean();
svrBean.setAddress("http://localhost/Hello");
svrBean.setTransportId("http://schemas.xmlsoap.org/soap/http");
svrBean.setServiceBean(new HelloServiceImpl());
svrBean.setServiceClass(HelloService.class);
svrBean.setBus(getBus());
svrBean.create();
ClientProxyFactoryBean proxyFactory=new ClientProxyFactoryBean();
ClientFactoryBean clientBean=proxyFactory.getClientFactoryBean();
clientBean.setAddress("http://localhost/Hello");
clientBean.setTransportId("http://schemas.xmlsoap.org/soap/http");
clientBean.setServiceClass(HelloService.class);
clientBean.setBus(getBus());
clientBean.getInInterceptors().add(new LoggingInInterceptor());
HelloService client=(HelloService)proxyFactory.create();
ClientImpl c=(ClientImpl)ClientProxy.getClient(client);
c.getOutInterceptors().add(new LoggingOutInterceptor());
c.getInInterceptors().add(new LoggingInInterceptor());
assertEquals("hello",client.sayHello());
assertEquals("hello",client.echo("hello"));
}
Class: org.apache.cxf.service.factory.ServerFactoryTest BooleanVerifier InternalCallVerifier
@Test public void testSetDF() throws Exception {
ServerFactoryBean svrBean=new ServerFactoryBean();
svrBean.setAddress("http://localhost/Hello");
svrBean.setServiceClass(HelloService.class);
svrBean.setServiceBean(new HelloServiceImpl());
svrBean.setBus(getBus());
svrBean.setDestinationFactory(new CustomDestinationFactory(getBus()));
ServerImpl server=(ServerImpl)svrBean.create();
assertTrue(server.getDestination() instanceof CustomDestination);
}
InternalCallVerifier EqualityVerifier
@Test public void testJaxbExtraClass() throws Exception {
ServerFactoryBean svrBean=new ServerFactoryBean();
svrBean.setAddress("http://localhost/Hello");
svrBean.setServiceClass(HelloServiceImpl.class);
svrBean.setBus(getBus());
Map props=svrBean.getProperties();
if (props == null) {
props=new HashMap();
}
props.put("jaxb.additionalContextClasses",new Class[]{GreetMe.class,GreetMeOneWay.class});
svrBean.setProperties(props);
Server serv=svrBean.create();
Class>[] extraClass=((JAXBDataBinding)serv.getEndpoint().getService().getDataBinding()).getExtraClass();
assertEquals(extraClass.length,2);
assertEquals(extraClass[0],GreetMe.class);
assertEquals(extraClass[1],GreetMeOneWay.class);
}
Class: org.apache.cxf.service.model.BindingFaultInfoTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBindingFaultInfo(){
assertNotNull(bindingFaultInfo.getFaultInfo());
assertNull(bindingFaultInfo.getBindingOperation());
assertEquals(bindingFaultInfo.getFaultInfo().getFaultName(),new QName("http://faultns/","fault"));
assertEquals(bindingFaultInfo.getFaultInfo().getName().getLocalPart(),"faultMessage");
assertEquals(bindingFaultInfo.getFaultInfo().getName().getNamespaceURI(),"http://apache.org/hello_world_soap_http");
}
Class: org.apache.cxf.service.model.BindingMessageInfoTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testMessage(){
assertNotNull(bindingMessageInfo.getMessageInfo());
assertEquals(bindingMessageInfo.getMessageInfo().getName().getLocalPart(),"testMessage");
assertEquals(bindingMessageInfo.getMessageInfo().getName().getNamespaceURI(),"http://apache.org/hello_world_soap_http");
assertNull(bindingMessageInfo.getBindingOperation());
}
Class: org.apache.cxf.service.model.BindingOperationInfoTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testInputMessage() throws Exception {
BindingMessageInfo inputMessage=bindingOperationInfo.getInput();
assertNotNull(inputMessage);
assertEquals(inputMessage.getMessageInfo().getName().getLocalPart(),"testInputMessage");
assertEquals(inputMessage.getMessageInfo().getName().getNamespaceURI(),"http://apache.org/hello_world_soap_http");
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testOutputMessage() throws Exception {
BindingMessageInfo outputMessage=bindingOperationInfo.getOutput();
assertNotNull(outputMessage);
assertEquals(outputMessage.getMessageInfo().getName().getLocalPart(),"testOutputMessage");
assertEquals(outputMessage.getMessageInfo().getName().getNamespaceURI(),"http://apache.org/hello_world_soap_http");
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testOperation() throws Exception {
assertEquals(bindingOperationInfo.getOperationInfo().getName(),new QName(TEST_NS,"operationTest"));
assertTrue(bindingOperationInfo.getOperationInfo().hasInput());
assertTrue(bindingOperationInfo.getOperationInfo().hasOutput());
assertEquals(bindingOperationInfo.getOperationInfo().getInputName(),"input");
assertEquals(bindingOperationInfo.getOperationInfo().getOutputName(),"output");
assertEquals(bindingOperationInfo.getFaults().iterator().next().getFaultInfo().getFaultName(),new QName(TEST_NS,"fault"));
assertEquals(1,bindingOperationInfo.getFaults().size());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testFaultMessage() throws Exception {
BindingFaultInfo faultMessage=bindingOperationInfo.getFaults().iterator().next();
assertNotNull(faultMessage);
assertEquals(faultMessage.getFaultInfo().getName().getLocalPart(),"faultMessage");
assertEquals(faultMessage.getFaultInfo().getName().getNamespaceURI(),"http://apache.org/hello_world_soap_http");
}
Class: org.apache.cxf.service.model.FaultInfoTest InternalCallVerifier EqualityVerifier
@Test public void testName() throws Exception {
assertEquals(faultInfo.getFaultName(),new QName("urn:test:ns","fault"));
assertEquals(faultInfo.getName().getLocalPart(),"faultMessage");
assertEquals(faultInfo.getName().getNamespaceURI(),"http://apache.org/hello_world_soap_http");
faultInfo.setFaultName(new QName("urn:test:ns","fault"));
assertEquals(faultInfo.getFaultName(),new QName("urn:test:ns","fault"));
}
Class: org.apache.cxf.service.model.InterfaceInfoTest BranchVerifier UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testOperation() throws Exception {
QName name=new QName("urn:test:ns","sayHi");
interfaceInfo.addOperation(name);
assertEquals("sayHi",interfaceInfo.getOperation(name).getName().getLocalPart());
interfaceInfo.addOperation(new QName("urn:test:ns","greetMe"));
assertEquals(interfaceInfo.getOperations().size(),2);
boolean duplicatedOperationName=false;
try {
interfaceInfo.addOperation(name);
}
catch ( IllegalArgumentException e) {
assertEquals(e.getMessage(),"An operation with name [{urn:test:ns}sayHi] already exists in this service");
duplicatedOperationName=true;
}
if (!duplicatedOperationName) {
fail("should get IllegalArgumentException");
}
boolean isNull=false;
try {
QName qname=null;
interfaceInfo.addOperation(qname);
}
catch ( NullPointerException e) {
isNull=true;
assertEquals(e.getMessage(),"Operation Name cannot be null.");
}
if (!isNull) {
fail("should get NullPointerException");
}
}
InternalCallVerifier EqualityVerifier
@Test public void testName() throws Exception {
assertEquals(interfaceInfo.getName().getLocalPart(),"interfaceTest");
assertEquals(interfaceInfo.getName().getNamespaceURI(),"http://apache.org/hello_world_soap_http");
QName qname=new QName("http://apache.org/hello_world_soap_http1","interfaceTest1");
interfaceInfo.setName(qname);
assertEquals(interfaceInfo.getName().getLocalPart(),"interfaceTest1");
assertEquals(interfaceInfo.getName().getNamespaceURI(),"http://apache.org/hello_world_soap_http1");
}
Class: org.apache.cxf.service.model.MessageInfoTest InternalCallVerifier EqualityVerifier
@Test public void testName() throws Exception {
assertEquals(messageInfo.getName().getLocalPart(),"testMessage");
assertEquals(messageInfo.getName().getNamespaceURI(),"http://apache.org/hello_world_soap_http");
}
InternalCallVerifier EqualityVerifier
@Test public void testMessagePartInfo() throws Exception {
QName qname=new QName("http://apache.org/hello_world_soap_http","testMessagePart");
messageInfo.addMessagePart(qname);
assertEquals(messageInfo.getMessageParts().size(),1);
MessagePartInfo messagePartInfo=messageInfo.getMessagePart(qname);
int indexAssigned=messagePartInfo.getIndex();
assertEquals(messagePartInfo.getName().getLocalPart(),"testMessagePart");
assertEquals(messagePartInfo.getName().getNamespaceURI(),"http://apache.org/hello_world_soap_http");
assertEquals(messagePartInfo.getMessageInfo(),messageInfo);
messagePartInfo=new MessagePartInfo(new QName("http://apache.org/hello_world_soap_http","testMessagePart"),messageInfo);
messageInfo.addMessagePart(messagePartInfo);
assertEquals(messageInfo.getMessageParts().size(),1);
assertEquals(indexAssigned,messagePartInfo.getIndex());
messagePartInfo=new MessagePartInfo(new QName("http://apache.org/hello_world_soap_http","testMessagePart2"),messageInfo);
messageInfo.addMessagePart(messagePartInfo);
assertEquals(messageInfo.getMessageParts().size(),2);
}
Class: org.apache.cxf.service.model.MessagePartInfoTest InternalCallVerifier EqualityVerifier
@Test public void testName() throws Exception {
assertEquals(messagePartInfo.getName().getLocalPart(),"testMessagePart");
assertEquals(messagePartInfo.getName().getNamespaceURI(),"http://apache.org/hello_world_soap_http");
messagePartInfo.setName(new QName("http://apache.org/hello_world_soap_http1","testMessagePart1"));
assertEquals(messagePartInfo.getName().getLocalPart(),"testMessagePart1");
assertEquals(messagePartInfo.getName().getNamespaceURI(),"http://apache.org/hello_world_soap_http1");
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testElement(){
messagePartInfo.setElementQName(new QName("http://apache.org/hello_world_soap_http/types","testElement"));
assertTrue(messagePartInfo.isElement());
assertEquals(messagePartInfo.getElementQName().getLocalPart(),"testElement");
assertEquals(messagePartInfo.getElementQName().getNamespaceURI(),"http://apache.org/hello_world_soap_http/types");
assertNull(messagePartInfo.getTypeQName());
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testType(){
messagePartInfo.setTypeQName(new QName("http://apache.org/hello_world_soap_http/types","testType"));
assertNull(messagePartInfo.getElementQName());
assertFalse(messagePartInfo.isElement());
assertEquals(messagePartInfo.getTypeQName().getLocalPart(),"testType");
assertEquals(messagePartInfo.getTypeQName().getNamespaceURI(),"http://apache.org/hello_world_soap_http/types");
}
Class: org.apache.cxf.service.model.OperationInfoTest UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testFault() throws Exception {
assertEquals(operationInfo.getFaults().size(),0);
QName faultName=new QName("urn:test:ns","fault");
operationInfo.addFault(faultName,new QName("http://apache.org/hello_world_soap_http","faultMessage"));
assertEquals(operationInfo.getFaults().size(),1);
FaultInfo fault=operationInfo.getFault(faultName);
assertNotNull(fault);
assertEquals(fault.getFaultName().getLocalPart(),"fault");
assertEquals(fault.getName().getLocalPart(),"faultMessage");
assertEquals(fault.getName().getNamespaceURI(),"http://apache.org/hello_world_soap_http");
operationInfo.removeFault(faultName);
assertEquals(operationInfo.getFaults().size(),0);
try {
operationInfo.addFault(null,null);
fail("should get NullPointerException");
}
catch ( NullPointerException e) {
assertEquals("Fault Name cannot be null.",e.getMessage());
}
try {
operationInfo.addFault(faultName,null);
operationInfo.addFault(faultName,null);
fail("should get IllegalArgumentException");
}
catch ( IllegalArgumentException e) {
assertEquals(e.getMessage(),"A fault with name [{urn:test:ns}fault] already exists in this operation");
}
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testOutput() throws Exception {
assertFalse(operationInfo.hasOutput());
MessageInfo outputMessage=operationInfo.createMessage(new QName("http://apache.org/hello_world_soap_http","testOutputMessage"),MessageInfo.Type.OUTPUT);
operationInfo.setOutput("output",outputMessage);
assertTrue(operationInfo.hasOutput());
outputMessage=operationInfo.getOutput();
assertEquals("testOutputMessage",outputMessage.getName().getLocalPart());
assertEquals("http://apache.org/hello_world_soap_http",outputMessage.getName().getNamespaceURI());
assertEquals(operationInfo.getOutputName(),"output");
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testInput() throws Exception {
assertFalse(operationInfo.hasInput());
MessageInfo inputMessage=operationInfo.createMessage(new QName("http://apache.org/hello_world_soap_http","testInputMessage"),MessageInfo.Type.INPUT);
operationInfo.setInput("input",inputMessage);
assertTrue(operationInfo.hasInput());
inputMessage=operationInfo.getInput();
assertEquals("testInputMessage",inputMessage.getName().getLocalPart());
assertEquals("http://apache.org/hello_world_soap_http",inputMessage.getName().getNamespaceURI());
assertEquals(operationInfo.getInputName(),"input");
}
UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testName() throws Exception {
assertNull(operationInfo.getInterface());
assertEquals("operationTest",operationInfo.getName().getLocalPart());
operationInfo.setName(new QName("urn:test:ns","operationTest2"));
assertEquals("operationTest2",operationInfo.getName().getLocalPart());
try {
operationInfo.setName(null);
fail("should catch IllegalArgumentException since name is null");
}
catch ( NullPointerException e) {
assertEquals(e.getMessage(),"Operation Name cannot be null.");
}
}
BooleanVerifier InternalCallVerifier
@Test public void testOneWay() throws Exception {
assertFalse(operationInfo.isOneWay());
MessageInfo inputMessage=operationInfo.createMessage(new QName("http://apache.org/hello_world_soap_http","testInputMessage"),MessageInfo.Type.INPUT);
operationInfo.setInput("input",inputMessage);
assertTrue(operationInfo.isOneWay());
}
Class: org.apache.cxf.staxutils.DepthXMLStreamReaderTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testReader() throws Exception {
XMLStreamReader reader=StaxUtils.createXMLStreamReader(getClass().getResourceAsStream("./resources/amazon.xml"));
DepthXMLStreamReader dr=new DepthXMLStreamReader(reader);
StaxUtils.toNextElement(dr);
assertEquals("ItemLookup",dr.getLocalName());
assertEquals(XMLStreamReader.START_ELEMENT,reader.getEventType());
assertEquals(1,dr.getDepth());
assertEquals(0,dr.getAttributeCount());
dr.next();
assertEquals(1,dr.getDepth());
assertTrue(dr.isWhiteSpace());
dr.nextTag();
assertEquals(2,dr.getDepth());
assertEquals("SubscriptionId",dr.getLocalName());
dr.next();
assertEquals("1E5AY4ZG53H4AMC8QH82",dr.getText());
dr.close();
}
Class: org.apache.cxf.staxutils.FragmentStreamReaderTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testReader() throws Exception {
XMLStreamReader reader=StaxUtils.createXMLStreamReader(getClass().getResourceAsStream("./resources/amazon.xml"));
DepthXMLStreamReader dr=new DepthXMLStreamReader(reader);
StaxUtils.toNextElement(dr);
assertEquals("ItemLookup",dr.getLocalName());
assertEquals(XMLStreamReader.START_ELEMENT,reader.getEventType());
FragmentStreamReader fsr=new FragmentStreamReader(dr);
assertTrue(fsr.hasNext());
assertEquals(XMLStreamReader.START_DOCUMENT,fsr.getEventType());
fsr.next();
assertEquals("ItemLookup",fsr.getLocalName());
assertEquals("ItemLookup",dr.getLocalName());
assertEquals(XMLStreamReader.START_ELEMENT,reader.getEventType());
fsr.close();
}
Class: org.apache.cxf.staxutils.PropertiesExpandingStreamReaderTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testSystemPropertyExpansion() throws Exception {
Map map=new HashMap();
map.put("bar","BAR-VALUE");
map.put("blah","BLAH-VALUE");
XMLStreamReader reader=new PropertiesExpandingStreamReader(StaxUtils.createXMLStreamReader(getTestStream("./resources/sysprops.xml")),map);
Document doc=StaxUtils.read(reader);
Element abc=DOMUtils.getChildrenWithName(doc.getDocumentElement(),"http://foo/bar","abc").iterator().next();
assertEquals("fooBAR-VALUEfoo",abc.getTextContent());
Element def=DOMUtils.getChildrenWithName(doc.getDocumentElement(),"http://foo/bar","def").iterator().next();
assertEquals("ggggg",def.getTextContent());
assertEquals("BLAH-VALUE2",def.getAttribute("myAttr"));
}
Class: org.apache.cxf.staxutils.StaxStreamFilterTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testFilterRPC() throws Exception {
StaxStreamFilter filter=new StaxStreamFilter(new QName[]{SOAP_ENV,SOAP_BODY});
String soapMessage="./resources/greetMeRpcLitReq.xml";
XMLStreamReader reader=StaxUtils.createXMLStreamReader(getTestStream(soapMessage));
reader=StaxUtils.createFilteredReader(reader,filter);
DepthXMLStreamReader dr=new DepthXMLStreamReader(reader);
StaxUtils.toNextElement(dr);
assertEquals(new QName("http://apache.org/hello_world_rpclit","sendReceiveData"),dr.getName());
StaxUtils.nextEvent(dr);
StaxUtils.toNextElement(dr);
assertEquals(new QName("","in"),dr.getName());
StaxUtils.nextEvent(dr);
StaxUtils.toNextElement(dr);
assertEquals(new QName("http://apache.org/hello_world_rpclit/types","elem1"),dr.getName());
StaxUtils.nextEvent(dr);
StaxUtils.toNextText(dr);
assertEquals("this is element 1",dr.getText());
StaxUtils.toNextElement(dr);
assertEquals(new QName("http://apache.org/hello_world_rpclit/types","elem1"),dr.getName());
assertEquals(XMLStreamConstants.END_ELEMENT,dr.getEventType());
StaxUtils.nextEvent(dr);
StaxUtils.toNextElement(dr);
assertEquals(new QName("http://apache.org/hello_world_rpclit/types","elem2"),dr.getName());
}
Class: org.apache.cxf.staxutils.StaxUtilsTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testToNextTag() throws Exception {
String soapMessage="./resources/headerSoapReq.xml";
XMLStreamReader r=StaxUtils.createXMLStreamReader(getTestStream(soapMessage));
DepthXMLStreamReader reader=new DepthXMLStreamReader(r);
reader.nextTag();
StaxUtils.toNextTag(reader,new QName("http://schemas.xmlsoap.org/soap/envelope/","Body"));
assertEquals("Body",reader.getLocalName());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testToNextElement(){
String soapMessage="./resources/sayHiRpcLiteralReq.xml";
XMLStreamReader r=StaxUtils.createXMLStreamReader(getTestStream(soapMessage));
DepthXMLStreamReader reader=new DepthXMLStreamReader(r);
assertTrue(StaxUtils.toNextElement(reader));
assertEquals("Envelope",reader.getLocalName());
StaxUtils.nextEvent(reader);
assertTrue(StaxUtils.toNextElement(reader));
assertEquals("Body",reader.getLocalName());
}
Class: org.apache.cxf.staxutils.W3CDOMStreamReaderTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testTopLevelText() throws Exception {
ByteArrayInputStream is=new ByteArrayInputStream("gorilla ".getBytes("utf-8"));
Document doc=StaxUtils.read(is);
Element e=doc.getDocumentElement();
XMLStreamReader reader=StaxUtils.createXMLStreamReader(e);
String value=reader.getElementText();
assertEquals("gorilla",value);
}
Class: org.apache.cxf.staxutils.transform.DelegatingNamespaceContextTest UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSomeAddsAndGets() throws Exception {
DelegatingNamespaceContext dnc=getTestDelegatingNamespaceContext();
dnc.down();
dnc.addPrefix("p1","urn:foo1");
dnc.addPrefix("p2","urn:foo2");
assertEquals("urn:foo0",dnc.getNamespaceURI("p0"));
assertEquals("urn:foo1",dnc.getNamespaceURI("p1"));
assertEquals("urn:foo2",dnc.getNamespaceURI("p2"));
assertEquals("p0",dnc.getPrefix("urn:foo0"));
assertEquals("p1",dnc.getPrefix("urn:foo1"));
assertEquals("p2",dnc.getPrefix("urn:foo2"));
verifyPrefixes(dnc.getPrefixes("urn:foo1"),new String[]{"p1"});
verifyPrefixes(dnc.getPrefixes("urn:foo2"),new String[]{"p2"});
dnc.down();
dnc.addPrefix("p11","urn:foo1");
dnc.addPrefix("p2","urn:foo22");
dnc.addPrefix("p3","urn:foo3");
assertEquals("urn:foo1",dnc.getNamespaceURI("p1"));
assertEquals("urn:foo1",dnc.getNamespaceURI("p11"));
assertEquals("urn:foo22",dnc.getNamespaceURI("p2"));
assertEquals("urn:foo3",dnc.getNamespaceURI("p3"));
String p=dnc.getPrefix("urn:foo1");
assertTrue("p1".equals(p) || "p11".equals(p));
assertNull(dnc.getPrefix("urn:foo2"));
assertEquals("p2",dnc.getPrefix("urn:foo22"));
assertEquals("p3",dnc.getPrefix("urn:foo3"));
p=dnc.findUniquePrefix("urn:foo4");
assertNotNull(p);
assertEquals(p,dnc.getPrefix("urn:foo4"));
assertEquals("urn:foo4",dnc.getNamespaceURI(p));
verifyPrefixes(dnc.getPrefixes("urn:foo1"),new String[]{"p1","p11"});
verifyPrefixes(dnc.getPrefixes("urn:foo2"),new String[]{});
verifyPrefixes(dnc.getPrefixes("urn:foo22"),new String[]{"p2"});
verifyPrefixes(dnc.getPrefixes("urn:foo3"),new String[]{"p3"});
dnc.up();
assertEquals("urn:foo1",dnc.getNamespaceURI("p1"));
assertNull(dnc.getNamespaceURI("p11"));
assertEquals("urn:foo2",dnc.getNamespaceURI("p2"));
assertNull(dnc.getNamespaceURI("p3"));
assertEquals("p1",dnc.getPrefix("urn:foo1"));
assertNull(dnc.getPrefix("urn:foo11"));
assertEquals("p2",dnc.getPrefix("urn:foo2"));
assertNull(dnc.getPrefix("urn:foo22"));
assertNull(dnc.getPrefix("urn:foo3"));
verifyPrefixes(dnc.getPrefixes("urn:foo1"),new String[]{"p1"});
verifyPrefixes(dnc.getPrefixes("urn:foo2"),new String[]{"p2"});
verifyPrefixes(dnc.getPrefixes("urn:foo3"),new String[]{});
dnc.up();
try {
dnc.up();
fail("not allowed to go up");
}
catch ( Exception e) {
}
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testSomeAddsWithDuplicatedPrefixName() throws Exception {
DelegatingNamespaceContext dnc=getTestDelegatingNamespaceContext();
dnc.down();
dnc.addPrefix("p00","urn:foo0");
dnc.addPrefix("p1","urn:foo1");
dnc.addPrefix("p2","urn:foo2");
assertEquals("urn:foo0",dnc.getNamespaceURI("p0"));
assertEquals("urn:foo0",dnc.getNamespaceURI("p00"));
assertEquals("urn:foo1",dnc.getNamespaceURI("p1"));
assertEquals("urn:foo2",dnc.getNamespaceURI("p2"));
assertTrue("p0".equals(dnc.getPrefix("urn:foo0")) || "p00".equals(dnc.getPrefix("urn:foo0")));
assertEquals("p1",dnc.getPrefix("urn:foo1"));
assertEquals("p2",dnc.getPrefix("urn:foo2"));
verifyPrefixes(dnc.getPrefixes("urn:foo1"),new String[]{"p1"});
verifyPrefixes(dnc.getPrefixes("urn:foo2"),new String[]{"p2"});
verifyPrefixes(dnc.getPrefixes("urn:foo0"),new String[]{"p0","p00"});
}
Class: org.apache.cxf.staxutils.transform.OutTransformWriterTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testNamespaceConversion() throws Exception {
W3CDOMStreamWriter writer=new W3CDOMStreamWriter();
JAXBContext context=JAXBContext.newInstance(TestBean.class);
Marshaller m=context.createMarshaller();
Map outMap=new HashMap();
outMap.put("{http://testbeans.com}testBean","{http://testbeans.com/v2}testBean");
outMap.put("{http://testbeans.com}bean","{http://testbeans.com/v3}bean");
OutTransformWriter transformWriter=new OutTransformWriter(writer,outMap,Collections.emptyMap(),Collections.emptyList(),false,"");
m.marshal(new TestBean(),transformWriter);
Element el=writer.getDocument().getDocumentElement();
assertEquals("http://testbeans.com/v2",el.getNamespaceURI());
assertFalse(StringUtils.isEmpty(el.getPrefix()));
Element el2=DOMUtils.getFirstElement(el);
assertEquals("http://testbeans.com/v3",el2.getNamespaceURI());
assertFalse(StringUtils.isEmpty(el2.getPrefix()));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testNamespaceConversionAndDefaultNS() throws Exception {
W3CDOMStreamWriter writer=new W3CDOMStreamWriter();
Map outMap=new HashMap();
outMap.put("{http://testbeans.com}testBean","{http://testbeans.com/v2}testBean");
outMap.put("{http://testbeans.com}bean","{http://testbeans.com/v3}bean");
OutTransformWriter transformWriter=new OutTransformWriter(writer,outMap,Collections.emptyMap(),Collections.emptyList(),false,"http://testbeans.com/v2");
JAXBContext context=JAXBContext.newInstance(TestBean.class);
Marshaller m=context.createMarshaller();
m.marshal(new TestBean(),transformWriter);
Element el=writer.getDocument().getDocumentElement();
assertEquals("http://testbeans.com/v2",el.getNamespaceURI());
assertTrue(StringUtils.isEmpty(el.getPrefix()));
el=DOMUtils.getFirstElement(el);
assertEquals("http://testbeans.com/v3",el.getNamespaceURI());
assertFalse(StringUtils.isEmpty(el.getPrefix()));
}
Class: org.apache.cxf.sts.claims.mapper.JexlClaimsMapperTest BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testRoleMappings() throws IOException {
ProcessedClaimCollection result=jcm.mapClaims("A",createClaimCollection(),"B",createProperties());
assertNotNull(result);
assertTrue(result.size() >= 1);
assertEquals(2,result.get(0).getValues().size());
assertTrue(result.get(0).getValues().contains("manager"));
assertTrue(result.get(0).getValues().contains("administrator"));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSingleToMultiValue() throws IOException {
ProcessedClaimCollection result=jcm.mapClaims("A",createClaimCollection(),"B",createProperties());
assertNotNull(result);
ProcessedClaim claim=findClaim(result,"http://my.schema.org/identity/claims/single2multi");
assertNotNull(claim);
assertNotNull(claim.getValues());
assertEquals(3,claim.getValues().size());
assertEquals("Value2",claim.getValues().get(1));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testMultiToSingleValue() throws IOException {
ProcessedClaimCollection result=jcm.mapClaims("A",createClaimCollection(),"B",createProperties());
assertNotNull(result);
ProcessedClaim claim=findClaim(result,"http://my.schema.org/identity/claims/multi2single");
assertNotNull(claim);
assertNotNull(claim.getValues());
assertEquals(1,claim.getValues().size());
assertEquals("Value1,Value2,Value3",claim.getValues().get(0));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testValueFilter() throws IOException {
ProcessedClaimCollection result=jcm.mapClaims("A",createClaimCollection(),"B",createProperties());
assertNotNull(result);
ProcessedClaim claim=findClaim(result,"http://my.schema.org/identity/claims/filter");
assertEquals(2,claim.getValues().size());
assertTrue(claim.getValues().contains("match"));
assertTrue(claim.getValues().contains("second_match"));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSimpleClaimCopy() throws IOException {
ProcessedClaimCollection result=jcm.mapClaims("A",createClaimCollection(),"B",createProperties());
assertNotNull(result);
ProcessedClaim claim=findClaim(result,"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/mail");
assertNotNull(claim);
assertNotNull(claim.getValues());
assertEquals(1,claim.getValues().size());
assertEquals("test@apache.com",claim.getValues().get(0));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testWrappedUpperCaseClaim() throws IOException {
ProcessedClaimCollection result=jcm.mapClaims("A",createClaimCollection(),"B",createProperties());
assertNotNull(result);
ProcessedClaim claim=findClaim(result,"http://my.schema.org/identity/claims/wrappedUppercase");
assertNotNull(claim);
assertNotNull(claim.getValues());
assertEquals(1,claim.getValues().size());
assertEquals("PREFIX_VALUE_SUFFIX",claim.getValues().get(0));
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testUpdateIssuer() throws IOException {
ProcessedClaimCollection result=jcm.mapClaims("A",createClaimCollection(),"B",createProperties());
assertNotNull(result);
assertEquals("STS-B",result.get(0).getOriginalIssuer());
assertEquals("NewIssuer",result.get(0).getIssuer());
assertEquals("STS-A",result.get(1).getOriginalIssuer());
}
APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testStaticClaim() throws IOException {
ProcessedClaimCollection result=jcm.mapClaims("A",createClaimCollection(),"B",createProperties());
assertNotNull(result);
ProcessedClaim staticClaim=findClaim(result,"http://schemas.microsoft.com/identity/claims/identityprovider");
assertNotNull(staticClaim);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testLowerCaseClaim() throws IOException {
ProcessedClaimCollection result=jcm.mapClaims("A",createClaimCollection(),"B",createProperties());
assertNotNull(result);
ProcessedClaim claim=findClaim(result,"http://my.schema.org/identity/claims/lowercase");
assertNotNull(claim);
assertNotNull(claim.getValues());
assertEquals(2,claim.getValues().size());
assertEquals("value2",claim.getValues().get(1));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testUpperCaseClaim() throws IOException {
ProcessedClaimCollection result=jcm.mapClaims("A",createClaimCollection(),"B",createProperties());
assertNotNull(result);
ProcessedClaim claim=findClaim(result,"http://my.schema.org/identity/claims/uppercase");
assertNotNull(claim);
assertNotNull(claim.getValues());
assertEquals(2,claim.getValues().size());
assertEquals("VALUE2",claim.getValues().get(1));
}
BranchVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testClaimMerge() throws IOException {
ProcessedClaimCollection result=jcm.mapClaims("A",createClaimCollection(),"B",createProperties());
assertNotNull(result);
assertTrue(result.size() >= 2);
assertEquals("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name",result.get(1).getClaimType().toString());
assertEquals(1,result.get(1).getValues().size());
assertEquals("Jan Bernhardt",result.get(1).getValues().get(0));
for ( ProcessedClaim c : result) {
if ("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname".equals(c.getClaimType())) {
fail("Only merged claim should be in result set, but not the individual claims");
}
}
}
Class: org.apache.cxf.systest.aegis.AegisClientServerTest InternalCallVerifier EqualityVerifier
@Test public void testCollection() throws Exception {
AegisDatabinding aegisBinding=new AegisDatabinding();
JaxWsProxyFactoryBean proxyFactory=new JaxWsProxyFactoryBean();
proxyFactory.setDataBinding(aegisBinding);
proxyFactory.setServiceClass(SportsService.class);
proxyFactory.setWsdlLocation("http://localhost:" + PORT + "/jaxwsAndAegisSports?wsdl");
proxyFactory.getInInterceptors().add(new LoggingInInterceptor());
proxyFactory.getOutInterceptors().add(new LoggingOutInterceptor());
SportsService service=(SportsService)proxyFactory.create();
Collection teams=service.getTeams();
assertEquals(1,teams.size());
assertEquals("Patriots",teams.iterator().next().getName());
String s=service.testForMinOccurs0("A",null,"b");
assertEquals("Anullb",s);
}
InternalCallVerifier EqualityVerifier
@Test public void testQualifiedPair() throws Exception {
AegisDatabinding aegisBinding=new AegisDatabinding();
JaxWsProxyFactoryBean proxyFactory=new JaxWsProxyFactoryBean();
proxyFactory.setDataBinding(aegisBinding);
proxyFactory.setServiceClass(SportsService.class);
proxyFactory.setAddress("http://localhost:" + PORT + "/jaxwsAndAegisSports");
proxyFactory.getInInterceptors().add(new LoggingInInterceptor());
proxyFactory.getOutInterceptors().add(new LoggingOutInterceptor());
SportsService service=(SportsService)proxyFactory.create();
int ret=service.getQualifiedPair(new Pair(111,"ffang"));
assertEquals(111,ret);
}
InternalCallVerifier EqualityVerifier
@Test public void testGenericCollection() throws Exception {
AegisDatabinding aegisBinding=new AegisDatabinding();
JaxWsProxyFactoryBean proxyFactory=new JaxWsProxyFactoryBean();
proxyFactory.setDataBinding(aegisBinding);
proxyFactory.setServiceClass(SportsService.class);
proxyFactory.setAddress("http://localhost:" + PORT + "/jaxwsAndAegisSports");
proxyFactory.getInInterceptors().add(new LoggingInInterceptor());
proxyFactory.getOutInterceptors().add(new LoggingOutInterceptor());
SportsService service=(SportsService)proxyFactory.create();
List list=new ArrayList();
list.add("ffang");
String ret=service.getGeneric(list);
assertEquals(ret,"ffang");
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testDynamicClient() throws Exception {
DynamicClientFactory dcf=DynamicClientFactory.newInstance();
Client client=dcf.createClient("http://localhost:" + PORT + "/jaxwsAndAegisSports?wsdl&dynamic");
Object r=client.invoke("getAttributeBean")[0];
Method getAddrPlainString=r.getClass().getMethod("getAttrPlainString");
String s=(String)getAddrPlainString.invoke(r);
assertEquals("attrPlain",s);
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testComplexMapResult() throws Exception {
AegisDatabinding aegisBinding=new AegisDatabinding();
JaxWsProxyFactoryBean proxyFactory=new JaxWsProxyFactoryBean();
proxyFactory.setDataBinding(aegisBinding);
proxyFactory.setServiceClass(SportsService.class);
proxyFactory.setAddress("http://localhost:" + PORT + "/jaxwsAndAegisSports");
proxyFactory.getInInterceptors().add(new LoggingInInterceptor());
proxyFactory.getOutInterceptors().add(new LoggingOutInterceptor());
SportsService service=(SportsService)proxyFactory.create();
Map> result=service.testComplexMapResult();
assertEquals(result.size(),1);
assertTrue(result.containsKey("key1"));
assertNotNull(result.get("key1"));
assertEquals(result.toString(),"{key1={1=3}}");
}
InternalCallVerifier EqualityVerifier
@Test public void testReturnGenericPair() throws Exception {
AegisDatabinding aegisBinding=new AegisDatabinding();
JaxWsProxyFactoryBean proxyFactory=new JaxWsProxyFactoryBean();
proxyFactory.setDataBinding(aegisBinding);
proxyFactory.setServiceClass(SportsService.class);
proxyFactory.setAddress("http://localhost:" + PORT + "/jaxwsAndAegisSports");
proxyFactory.getInInterceptors().add(new LoggingInInterceptor());
proxyFactory.getOutInterceptors().add(new LoggingOutInterceptor());
SportsService service=(SportsService)proxyFactory.create();
int ret=service.getGenericPair(new Pair(111,"String"));
assertEquals(111,ret);
}
InternalCallVerifier EqualityVerifier
@Test public void testReturnQualifiedPair() throws Exception {
AegisDatabinding aegisBinding=new AegisDatabinding();
JaxWsProxyFactoryBean proxyFactory=new JaxWsProxyFactoryBean();
proxyFactory.setDataBinding(aegisBinding);
proxyFactory.setServiceClass(SportsService.class);
proxyFactory.setAddress("http://localhost:" + PORT + "/jaxwsAndAegisSports");
proxyFactory.getInInterceptors().add(new LoggingInInterceptor());
proxyFactory.getOutInterceptors().add(new LoggingOutInterceptor());
SportsService service=(SportsService)proxyFactory.create();
Pair ret=service.getReturnQualifiedPair(111,"ffang");
assertEquals(new Integer(111),ret.getFirst());
assertEquals("ffang",ret.getSecond());
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testAegisClient() throws Exception {
AegisDatabinding aegisBinding=new AegisDatabinding();
ClientProxyFactoryBean proxyFactory=new ClientProxyFactoryBean();
proxyFactory.setDataBinding(aegisBinding);
proxyFactory.setServiceClass(AuthService.class);
proxyFactory.setAddress("http://localhost:" + PORT + "/service");
AuthService service=(AuthService)proxyFactory.create();
assertTrue(service.authenticate("Joe","Joe","123"));
assertFalse(service.authenticate("Joe1","Joe","fang"));
assertTrue(service.authenticate("Joe",null,"123"));
List list=service.getRoles("Joe");
assertEquals(3,list.size());
assertEquals("Joe",list.get(0));
assertEquals("Joe-1",list.get(1));
assertEquals("Joe-2",list.get(2));
String roles[]=service.getRolesAsArray("Joe");
assertEquals(2,roles.length);
assertEquals("Joe",roles[0]);
assertEquals("Joe-1",roles[1]);
assertEquals("get Joe",service.getAuthentication("Joe"));
Authenticate au=new Authenticate();
au.setSid("ffang");
au.setUid("ffang");
assertTrue(service.authenticate(au));
au.setUid("ffang1");
assertFalse(service.authenticate(au));
}
InternalCallVerifier EqualityVerifier
@Test public void testGenericPair() throws Exception {
AegisDatabinding aegisBinding=new AegisDatabinding();
JaxWsProxyFactoryBean proxyFactory=new JaxWsProxyFactoryBean();
proxyFactory.setDataBinding(aegisBinding);
proxyFactory.setServiceClass(SportsService.class);
proxyFactory.setAddress("http://localhost:" + PORT + "/jaxwsAndAegisSports");
proxyFactory.getInInterceptors().add(new LoggingInInterceptor());
proxyFactory.getOutInterceptors().add(new LoggingOutInterceptor());
SportsService service=(SportsService)proxyFactory.create();
Pair ret=service.getReturnGenericPair("ffang",111);
assertEquals("ffang",ret.getFirst());
assertEquals(new Integer(111),ret.getSecond());
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testJaxWsAegisClient() throws Exception {
AegisDatabinding aegisBinding=new AegisDatabinding();
JaxWsProxyFactoryBean proxyFactory=new JaxWsProxyFactoryBean();
proxyFactory.setDataBinding(aegisBinding);
proxyFactory.setServiceClass(AuthService.class);
proxyFactory.setAddress("http://localhost:" + PORT + "/jaxwsAndAegis");
AuthService service=(AuthService)proxyFactory.create();
assertTrue(service.authenticate("Joe","Joe","123"));
assertFalse(service.authenticate("Joe1","Joe","fang"));
assertTrue(service.authenticate("Joe",null,"123"));
List list=service.getRoles("Joe");
assertEquals(3,list.size());
assertEquals("Joe",list.get(0));
assertEquals("Joe-1",list.get(1));
assertEquals("Joe-2",list.get(2));
String roles[]=service.getRolesAsArray("Joe");
assertEquals(2,roles.length);
assertEquals("Joe",roles[0]);
assertEquals("Joe-1",roles[1]);
roles=service.getRolesAsArray("null");
assertNull(roles);
roles=service.getRolesAsArray("0");
assertEquals(0,roles.length);
assertEquals("get Joe",service.getAuthentication("Joe"));
Authenticate au=new Authenticate();
au.setSid("ffang");
au.setUid("ffang");
assertTrue(service.authenticate(au));
au.setUid("ffang1");
assertFalse(service.authenticate(au));
}
Class: org.apache.cxf.systest.aegis.AegisJaxWsTest BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testByteArray() throws Exception {
int size=50;
List ints=new ArrayList(size);
for (int x=0; x < size; x++) {
ints.add(x);
}
setupForTest(false);
byte[] bytes=client.export(ints);
Assert.assertNotNull(bytes);
Assert.assertTrue(bytes.length > 50);
}
InternalCallVerifier EqualityVerifier
@Test public void testGetStringList() throws Exception {
setupForTest(false);
Integer soucet=client.getSimpleValue(5,"aa");
Assert.assertEquals(new Integer(5),soucet);
List item=client.getStringList();
Assert.assertEquals(Arrays.asList("a","b","c"),item);
}
InternalCallVerifier EqualityVerifier
@Test public void testBigList() throws Exception {
int size=1000;
List l=new ArrayList(size);
for (int x=0; x < size; x++) {
l.add("Need to create a pretty big soap message to make sure we go over " + "some of the default buffer sizes and such so we can see what really" + "happens when we do that - "+ x);
}
setupForTest(false);
List item=client.echoBigList(l);
Assert.assertEquals(size,item.size());
File f=FileUtils.getDefaultTempDir();
Assert.assertEquals(0,f.listFiles().length);
}
InternalCallVerifier EqualityVerifier
@Test public void testGetItem() throws Exception {
setupForTest(false);
Item item=client.getItemByKey(" a ","b");
Assert.assertEquals(33,item.getKey().intValue());
Assert.assertEquals(" a :b",item.getData());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetItemSecure() throws Exception {
setupForTest(true);
Item item=client.getItemByKey(" jack&jill ","b");
Assert.assertEquals(33,item.getKey().intValue());
Assert.assertEquals(" jack&jill :b",item.getData());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testMapSpecified() throws Exception {
setupForTest(false);
Item item=new Item();
item.setKey(new Integer(42));
item.setData("Godzilla");
client.addItem(item);
Map items=client.getItemsMapSpecified();
Assert.assertNotNull(items);
Assert.assertEquals(1,items.size());
Map.Entry entry=items.entrySet().iterator().next();
Assert.assertNotNull(entry);
Item item2=entry.getValue();
Integer key2=entry.getKey();
Assert.assertEquals(42,key2.intValue());
Assert.assertEquals("Godzilla",item2.getData());
}
Class: org.apache.cxf.systest.aegis.AegisWSDLNSTest InternalCallVerifier EqualityVerifier
@Test public void testUsingCorrectMethod() throws Exception {
setupForTest(false);
Integer result=client.updateInteger(new Integer(20));
Assert.assertEquals(result.intValue(),20);
}
Class: org.apache.cxf.systest.aegis.CharacterSchemaTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSchema() throws Exception {
testUtilities.setBus((Bus)applicationContext.getBean("cxf"));
testUtilities.addDefaultNamespaces();
testUtilities.addNamespace("aegis","http://cxf.apache.org/aegisTypes");
Server s=testUtilities.getServerForService(new QName("http://aegis.systest.cxf.apache.org/","SportsService"));
Assert.assertNotNull(s);
Document wsdl=testUtilities.getWSDLDocument(s);
Assert.assertNotNull(wsdl);
NodeList typeAttrList=testUtilities.assertValid("//xsd:complexType[@name='BeanWithCharacter']/xsd:sequence" + "/xsd:element[@name='character']" + "/@type",wsdl);
Attr typeAttr=(Attr)typeAttrList.item(0);
String typeAttrValue=typeAttr.getValue();
String[] pieces=typeAttrValue.split(":");
Assert.assertEquals(CharacterAsStringType.CHARACTER_AS_STRING_TYPE_QNAME.getLocalPart(),pieces[1]);
Node elementNode=typeAttr.getOwnerElement();
String url=testUtilities.resolveNamespacePrefix(pieces[0],elementNode);
Assert.assertEquals(CharacterAsStringType.CHARACTER_AS_STRING_TYPE_QNAME.getNamespaceURI(),url);
}
Class: org.apache.cxf.systest.aegis.mtom.MtomTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testMtomReply() throws Exception {
setupForTest(true);
DataHandlerBean dhBean=client.produceDataHandlerBean();
Assert.assertNotNull(dhBean);
String result=IOUtils.toString(dhBean.getDataHandler().getInputStream(),"utf-8");
Assert.assertEquals(MtomTestImpl.STRING_DATA,result);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testJaxWsMtomReply() throws Exception {
setupForTest(true);
DataHandlerBean dhBean=jaxwsClient.produceDataHandlerBean();
Assert.assertNotNull(dhBean);
String result=IOUtils.toString(dhBean.getDataHandler().getInputStream(),"utf-8");
Assert.assertEquals(MtomTestImpl.STRING_DATA,result);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testAcceptDataHandlerNoMTOM() throws Exception {
setupForTest(false);
DataHandlerBean dhBean=new DataHandlerBean();
dhBean.setName("some name");
String someData="This is the cereal shot from guns.";
DataHandler dataHandler=new DataHandler(someData,"text/plain;charset=utf-8");
dhBean.setDataHandler(dataHandler);
client.acceptDataHandler(dhBean);
DataHandlerBean accepted=impl.getLastDhBean();
Assert.assertNotNull(accepted);
InputStream data=accepted.getDataHandler().getInputStream();
Assert.assertNotNull(data);
String dataString=org.apache.commons.io.IOUtils.toString(data,"utf-8");
Assert.assertEquals("This is the cereal shot from guns.",dataString);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testAcceptDataHandler() throws Exception {
setupForTest(true);
DataHandlerBean dhBean=new DataHandlerBean();
dhBean.setName("some name");
String someData="This is the cereal shot from guns.";
DataHandler dataHandler=new DataHandler(someData,"text/plain;charset=utf-8");
dhBean.setDataHandler(dataHandler);
client.acceptDataHandler(dhBean);
DataHandlerBean accepted=impl.getLastDhBean();
Assert.assertNotNull(accepted);
Object o=accepted.getDataHandler().getContent();
String data=null;
if (o instanceof String) {
data=(String)o;
}
else if (o instanceof InputStream) {
data=IOUtils.toString((InputStream)o);
}
Assert.assertNotNull(data);
Assert.assertEquals("This is the cereal shot from guns.",data);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testMtomSchema() throws Exception {
testUtilities.setBus((Bus)applicationContext.getBean("cxf"));
testUtilities.addDefaultNamespaces();
testUtilities.addNamespace("xmime","http://www.w3.org/2005/05/xmlmime");
Server s=testUtilities.getServerForService(new QName("http://fortest.mtom.aegis.systest.cxf.apache.org/","MtomTestService"));
Document wsdl=testUtilities.getWSDLDocument(s);
Assert.assertNotNull(wsdl);
NodeList typeAttrList=testUtilities.assertValid("//xsd:complexType[@name='inputDhBean']/xsd:sequence/" + "xsd:element[@name='dataHandler']/" + "@type",wsdl);
Attr typeAttr=(Attr)typeAttrList.item(0);
String typeAttrValue=typeAttr.getValue();
String[] pieces=typeAttrValue.split(":");
Assert.assertEquals("base64Binary",pieces[1]);
Node elementNode=typeAttr.getOwnerElement();
String url=testUtilities.resolveNamespacePrefix(pieces[0],elementNode);
Assert.assertEquals(Constants.URI_2001_SCHEMA_XSD,url);
s=testUtilities.getServerForAddress("http://localhost:" + PORT + "/mtomXmime");
wsdl=testUtilities.getWSDLDocument(s);
Assert.assertNotNull(wsdl);
typeAttrList=testUtilities.assertValid("//xsd:complexType[@name='inputDhBean']/xsd:sequence/" + "xsd:element[@name='dataHandler']/" + "@type",wsdl);
typeAttr=(Attr)typeAttrList.item(0);
typeAttrValue=typeAttr.getValue();
pieces=typeAttrValue.split(":");
Assert.assertEquals("base64Binary",pieces[1]);
elementNode=typeAttr.getOwnerElement();
url=testUtilities.resolveNamespacePrefix(pieces[0],elementNode);
Assert.assertEquals(AbstractXOPType.XML_MIME_NS,url);
}
Class: org.apache.cxf.systest.basicDOCBare.DOCBareClientServerTest InternalCallVerifier NullVerifier
@Test public void testNillableParameter() throws Exception {
URL wsdl=getClass().getResource("/wsdl/doc_lit_bare.wsdl");
assertNotNull("WSDL is null",wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
assertNotNull("Service is null",service);
PutLastTradedPricePortType port=service.getPort(portName,PutLastTradedPricePortType.class);
updateAddressPort(port,PORT);
String result=port.nillableParameter(null);
assertNull(result);
}
IterativeVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBasicConnection() throws Exception {
URL wsdl=getClass().getResource("/wsdl/doc_lit_bare.wsdl");
assertNotNull("WSDL is null",wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
assertNotNull("Service is null",service);
PutLastTradedPricePortType putLastTradedPrice=service.getPort(portName,PutLastTradedPricePortType.class);
updateAddressPort(putLastTradedPrice,PORT);
String response=putLastTradedPrice.bareNoParam();
assertEquals("testResponse",response);
TradePriceData priceData=new TradePriceData();
priceData.setTickerPrice(1.0f);
priceData.setTickerSymbol("CELTIX");
Holder holder=new Holder(priceData);
for (int i=0; i < 5; i++) {
putLastTradedPrice.sayHi(holder);
assertEquals(4.5f,holder.value.getTickerPrice(),0.01);
assertEquals("APACHE",holder.value.getTickerSymbol());
putLastTradedPrice.putLastTradedPrice(priceData);
}
}
Class: org.apache.cxf.systest.bus.SpringBusFactoryTest InternalCallVerifier NullVerifier
@Test public void testKnownExtensions() throws BusException {
Bus bus=new SpringBusFactory().createBus();
assertNotNull(bus);
checkBindingExtensions(bus);
DestinationFactoryManager dfm=bus.getExtension(DestinationFactoryManager.class);
assertNotNull("No destination factory manager",dfm);
ConduitInitiatorManager cim=bus.getExtension(ConduitInitiatorManager.class);
assertNotNull("No conduit initiator manager",cim);
checkTransportFactories(bus);
checkOtherCoreExtensions(bus);
assertNotNull("No instrumentation manager",bus.getExtension(InstrumentationManager.class));
bus.shutdown(true);
}
Class: org.apache.cxf.systest.callback.CallbackClientServerTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testCallback() throws Exception {
Object implementor=new CallbackImpl();
String address="http://localhost:" + CB_PORT + "/CallbackContext/CallbackPort";
Endpoint ep=Endpoint.publish(address,implementor);
URL wsdlURL=getClass().getResource("/wsdl/basic_callback_test.wsdl");
SOAPService ss=new SOAPService(wsdlURL,SERVICE_NAME);
ServerPortType port=ss.getPort(PORT_NAME,ServerPortType.class);
updateAddressPort(port,PORT);
EndpointReference w3cEpr=ep.getEndpointReference();
String resp=port.registerCallback((W3CEndpointReference)w3cEpr);
assertEquals("registerCallback called",resp);
ep.stop();
}
Class: org.apache.cxf.systest.clustering.CircuitBreakerFailoverTest UtilityVerifier InternalCallVerifier NullVerifier ConditionMatcher HybridVerifier
@Test public void testWithAlternativeEnpdpoints() throws Exception {
final Greeter g=getGreeter(REPLICA_A);
startTarget(REPLICA_E);
try {
final String response=g.greetMe("fred");
assertNotNull("expected non-null response",response);
}
finally {
stopTarget(REPLICA_E);
}
try {
g.greetMe("fred");
fail("Expecting no alternative endpoints exception");
}
catch ( WebServiceException ex) {
assertThat(ex.getMessage(),equalTo("Could not send Message."));
}
}
Class: org.apache.cxf.systest.clustering.FailoverAddressOverrideTest BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testOverriddenSequentialStrategy() throws Exception {
startTarget(REPLICA_C);
setupGreeterA();
verifyStrategy(greeter,SequentialStrategy.class,3);
String response=greeter.greetMe("fred");
assertNotNull("expected non-null response",response);
assertTrue("response from unexpected target: " + response,response.endsWith(REPLICA_C));
verifyCurrentEndpoint(REPLICA_C);
stopTarget(REPLICA_C);
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testOverriddenRandomStrategy() throws Exception {
startTarget(REPLICA_B);
setupGreeterC();
verifyStrategy(greeter,RandomStrategy.class,3);
String response=greeter.greetMe("fred");
assertNotNull("expected non-null response",response);
assertTrue("response from unexpected target: " + response,response.endsWith(REPLICA_B));
verifyCurrentEndpoint(REPLICA_B);
stopTarget(REPLICA_B);
}
Class: org.apache.cxf.systest.clustering.FailoverTest BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testNoFailbackWhileCurrentReplicaLive() throws Exception {
startTarget(REPLICA_C);
setupGreeter();
String response=null;
response=greeter.greetMe("fred");
assertNotNull("expected non-null response",response);
assertTrue("response from unexpected target: " + response,response.endsWith(REPLICA_C));
verifyCurrentEndpoint(REPLICA_C);
startTarget(REPLICA_A);
response=greeter.greetMe("joe");
assertNotNull("expected non-null response",response);
assertTrue("response from unexpected target: " + response,response.endsWith(REPLICA_C));
verifyCurrentEndpoint(REPLICA_C);
startTarget(REPLICA_B);
response=greeter.greetMe("bob");
assertNotNull("expected non-null response",response);
assertTrue("response from unexpected target: " + response,response.endsWith(REPLICA_C));
verifyCurrentEndpoint(REPLICA_C);
stopTarget(REPLICA_B);
response=greeter.greetMe("john");
assertNotNull("expected non-null response",response);
assertTrue("response from unexpected target: " + response,response.endsWith(REPLICA_C));
verifyCurrentEndpoint(REPLICA_C);
stopTarget(REPLICA_A);
response=greeter.greetMe("mike");
assertNotNull("expected non-null response",response);
assertTrue("response from unexpected target: " + response,response.endsWith(REPLICA_C));
verifyCurrentEndpoint(REPLICA_C);
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testFailoverOnCurrentReplicaDeath() throws Exception {
startTarget(REPLICA_C);
setupGreeter();
String response=null;
response=greeter.greetMe("fred");
assertNotNull("expected non-null response",response);
assertTrue("response from unexpected target: " + response,response.endsWith(REPLICA_C));
verifyCurrentEndpoint(REPLICA_C);
startTarget(REPLICA_B);
stopTarget(REPLICA_C);
response=greeter.greetMe("joe");
assertNotNull("expected non-null response",response);
assertTrue("response from unexpected target: " + response,response.endsWith(REPLICA_B));
verifyCurrentEndpoint(REPLICA_B);
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testInitialFailoverOnPrimaryReplicaUnavailable() throws Exception {
startTarget(REPLICA_C);
setupGreeter();
String response=null;
response=greeter.greetMe("fred");
assertNotNull("expected non-null response",response);
assertTrue("response from unexpected target: " + response,response.endsWith(REPLICA_C));
verifyCurrentEndpoint(REPLICA_C);
response=greeter.greetMe("joe");
assertNotNull("expected non-null response",response);
assertTrue("response from unexpected target: " + response,response.endsWith(REPLICA_C));
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testEndpointSpecificInterceptorsDoNotPersistAcrossFailover() throws Exception {
startTarget(REPLICA_A);
setupGreeter();
String response=null;
enableWSAForCurrentEndpoint();
response=greeter.greetMe("fred");
assertNotNull("expected non-null response",response);
assertTrue("response from unexpected target: " + response,response.endsWith(REPLICA_A));
assertTrue("response expected to include WS-A messageID",response.indexOf("message: urn:uuid") != -1);
verifyCurrentEndpoint(REPLICA_A);
assertTrue("expected WSA enabled for current endpoint",isWSAEnabledForCurrentEndpoint());
stopTarget(REPLICA_A);
startTarget(REPLICA_C);
response=greeter.greetMe("mike");
assertNotNull("expected non-null response",response);
assertTrue("response from unexpected target: " + response,response.endsWith(REPLICA_C));
assertTrue("response not expected to include WS-A messageID",response.indexOf("message: urn:uuid") == -1);
verifyCurrentEndpoint(REPLICA_C);
assertFalse("unexpected WSA enabled for current endpoint",isWSAEnabledForCurrentEndpoint());
}
Class: org.apache.cxf.systest.corba.CorbaBindingFactoryConfigurerTest APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testOrbConfiguration() throws Exception {
SpringBusFactory bf=new SpringBusFactory();
URL cxfConfig=null;
cxfConfig=ClassLoaderUtils.getResource("corba_binding_factory_configurer.xml",this.getClass());
bus=bf.createBus(cxfConfig);
BusFactory.setDefaultBus(bus);
BindingFactoryManager bfm=bus.getExtension(BindingFactoryManager.class);
CorbaBindingFactory factory=(CorbaBindingFactory)bfm.getBindingFactory("http://cxf.apache.org/bindings/corba");
OrbConfig orbConfig=factory.getOrbConfig();
assertTrue("CorbaBindingFactoryConfigurer is null",orbConfig != null);
Properties props=orbConfig.getOrbProperties();
assertTrue("probs is null",props != null);
assertTrue("prob1 is not equal to value1","value1".equals(props.get("prop1")));
assertTrue("prob2 is not equal to value2","value2".equals(props.get("prop2")));
assertTrue("ORBClass is not equal to MyORBImpl","com.orbimplco.MyORBImpl".equals(props.get("org.omg.CORBA.ORBClass")));
assertTrue("ORBSingletonClass is not equal to MyORBSingleton","com.orbimplco.MyORBSingleton".equals(props.get("org.omg.CORBA.ORBSingletonClass")));
List orbArgs=orbConfig.getOrbArgs();
assertTrue("orbArgs is null",orbArgs != null);
String domainNameId=orbArgs.get(0);
assertTrue("domainNameId is not equal to -ORBdomain_name","-ORBdomain_name".equals(domainNameId));
String domainNameValue=orbArgs.get(1);
assertTrue("domainNameValue is not equal to test-domain","test-domain".equals(domainNameValue));
String configDomainsDirId=orbArgs.get(2);
assertTrue("configDomainsDirId is not equal to -ORBconfig_domains_dir","-ORBconfig_domains_dir".equals(configDomainsDirId));
String configDomainsDirValue=orbArgs.get(3);
assertTrue("configDomainsDirValue is not equal to src/test/resources","src/test/resources".equals(configDomainsDirValue));
String orbNameId=orbArgs.get(4);
assertTrue("orbNameId is not equal to -ORBname","-ORBname".equals(orbNameId));
String orbNameValue=orbArgs.get(5);
assertTrue("orbNameValue is not equal to test","test".equals(orbNameValue));
}
Class: org.apache.cxf.systest.corba.CorbaTest BooleanVerifier InternalCallVerifier
@Test public void testClientServer() throws Exception {
System.getProperties().remove("com.sun.CORBA.POA.ORBServerId");
System.getProperties().remove("com.sun.CORBA.POA.ORBPersistentServerPort");
URL wsdlUrl=this.getClass().getResource("/wsdl_systest/hello_world_corba.wsdl");
new SpringBusFactory().createBus("org/apache/cxf/systest/corba/hello_world_client.xml");
GreeterCORBAService gcs=new GreeterCORBAService(wsdlUrl,SERVICE_NAME);
Greeter port=gcs.getGreeterCORBAPort();
String output=port.greetMe("Betty");
assertTrue("Unexpected returned string: " + output,"Hello Betty".equals(output));
}
Class: org.apache.cxf.systest.dispatch.DispatchClientServerTest APIUtilityVerifier UtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testStreamSourcePAYLOADWithSchemaValidation() throws Exception {
URL wsdl=getClass().getResource("/org/apache/cxf/systest/provider/hello_world_with_restriction.wsdl");
assertNotNull(wsdl);
SOAPService service=new SOAPService(wsdl,SERVICE_NAME);
assertNotNull(service);
Dispatch disp=service.createDispatch(PORT_NAME,StreamSource.class,Service.Mode.PAYLOAD);
disp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"http://localhost:" + greeterPort + "/SOAPDispatchService/SoapDispatchPort");
disp.getRequestContext().put(Message.SCHEMA_VALIDATION_ENABLED,Boolean.TRUE);
InputStream is=getClass().getResourceAsStream("resources/GreetMeDocLiteralSOAPBodyReqExceedMaxLength.xml");
StreamSource streamSourceReq=new StreamSource(is);
assertNotNull(streamSourceReq);
try {
disp.invoke(streamSourceReq);
fail("Should have thrown an exception");
}
catch ( Exception ex) {
assertTrue(ex.getMessage().contains("cvc-maxLength-valid"));
}
is=getClass().getResourceAsStream("resources/GreetMeDocLiteralSOAPBodyReq.xml");
streamSourceReq=new StreamSource(is);
assertNotNull(streamSourceReq);
StreamSource streamSourceResp=disp.invoke(streamSourceReq);
assertNotNull(streamSourceResp);
String expected="Hello TestSOAPInputMessage";
assertTrue("Expected: " + expected,StaxUtils.toString(streamSourceResp).contains(expected));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testJAXBObjectPAYLOADWithFeature() throws Exception {
createBus("org/apache/cxf/systest/dispatch/client-config.xml");
BusFactory.setThreadDefaultBus(bus);
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
String bindingId="http://schemas.xmlsoap.org/wsdl/soap/";
String endpointUrl="http://localhost:" + greeterPort + "/SOAPDispatchService/SoapDispatchPort";
Service service=Service.create(wsdl,SERVICE_NAME);
service.addPort(PORT_NAME,bindingId,endpointUrl);
assertNotNull(service);
JAXBContext jc=JAXBContext.newInstance("org.apache.hello_world_soap_http.types");
Dispatch disp=service.createDispatch(PORT_NAME,jc,Service.Mode.PAYLOAD);
disp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"http://localhost:" + greeterPort + "/SOAPDispatchService/SoapDispatchPort");
String expected="Hello Jeeves";
GreetMe greetMe=new GreetMe();
greetMe.setRequestType("Jeeves");
Object response=disp.invoke(greetMe);
assertNotNull(response);
String responseValue=((GreetMeResponse)response).getResponseType();
assertTrue("Expected string, " + expected,expected.equals(responseValue));
assertEquals("Feature should be applied",1,TestDispatchFeature.getCount());
assertEquals("Feature based interceptors should be added",1,TestDispatchFeature.getCount());
assertEquals("Feature based In interceptors has be added to in chain.",1,TestDispatchFeature.getInInterceptorCount());
assertEquals("Feature based interceptors has to be added to out chain.",1,TestDispatchFeature.getOutInterceptorCount());
bus.shutdown(true);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testStreamSourceMESSAGE() throws Exception {
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
SOAPService service=new SOAPService(wsdl,SERVICE_NAME);
assertNotNull(service);
Dispatch disp=service.createDispatch(PORT_NAME,StreamSource.class,Service.Mode.MESSAGE);
disp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"http://localhost:" + greeterPort + "/SOAPDispatchService/SoapDispatchPort");
InputStream is=getClass().getResourceAsStream("resources/GreetMeDocLiteralReq.xml");
StreamSource streamSourceReq=new StreamSource(is);
assertNotNull(streamSourceReq);
StreamSource streamSourceResp=disp.invoke(streamSourceReq);
assertNotNull(streamSourceResp);
String expected="Hello TestSOAPInputMessage";
assertTrue("Expected: " + expected,StaxUtils.toString(streamSourceResp).contains(expected));
InputStream is1=getClass().getResourceAsStream("resources/GreetMeDocLiteralReq1.xml");
StreamSource streamSourceReq1=new StreamSource(is1);
assertNotNull(streamSourceReq1);
disp.invokeOneWay(streamSourceReq1);
InputStream is2=getClass().getResourceAsStream("resources/GreetMeDocLiteralReq2.xml");
StreamSource streamSourceReq2=new StreamSource(is2);
assertNotNull(streamSourceReq2);
Response response=disp.invokeAsync(streamSourceReq2);
StreamSource streamSourceResp2=response.get();
assertNotNull(streamSourceResp2);
String expected2="Hello TestSOAPInputMessage2";
assertTrue("Expected: " + expected,StaxUtils.toString(streamSourceResp2).contains(expected2));
InputStream is3=getClass().getResourceAsStream("resources/GreetMeDocLiteralReq3.xml");
StreamSource streamSourceReq3=new StreamSource(is3);
assertNotNull(streamSourceReq3);
TestStreamSourceHandler tssh=new TestStreamSourceHandler();
Future> fd=disp.invokeAsync(streamSourceReq3,tssh);
assertNotNull(fd);
waitForFuture(fd);
String expected3="Hello TestSOAPInputMessage3";
StreamSource streamSourceResp3=tssh.getStreamSource();
assertNotNull(streamSourceResp3);
assertTrue("Expected: " + expected,StaxUtils.toString(streamSourceResp3).contains(expected3));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testSAXSourcePAYLOAD() throws Exception {
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
SOAPService service=new SOAPService(wsdl,SERVICE_NAME);
assertNotNull(service);
Dispatch disp=service.createDispatch(PORT_NAME,SAXSource.class,Service.Mode.PAYLOAD);
disp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"http://localhost:" + greeterPort + "/SOAPDispatchService/SoapDispatchPort");
InputStream is=getClass().getResourceAsStream("resources/GreetMeDocLiteralSOAPBodyReq.xml");
InputSource inputSource=new InputSource(is);
inputSource.setPublicId(getClass().getResource("resources/GreetMeDocLiteralSOAPBodyReq.xml").toString());
inputSource.setSystemId(inputSource.getPublicId());
SAXSource saxSourceReq=new SAXSource(inputSource);
assertNotNull(saxSourceReq);
SAXSource saxSourceResp=disp.invoke(saxSourceReq);
assertNotNull(saxSourceResp);
String expected="Hello TestSOAPInputMessage";
assertTrue("Expected: " + expected,StaxUtils.toString(saxSourceResp).contains(expected));
InputStream is1=getClass().getResourceAsStream("resources/GreetMeDocLiteralSOAPBodyReq1.xml");
InputSource inputSource1=new InputSource(is1);
inputSource1.setPublicId(getClass().getResource("resources/GreetMeDocLiteralSOAPBodyReq1.xml").toString());
inputSource1.setSystemId(inputSource1.getPublicId());
SAXSource saxSourceReq1=new SAXSource(inputSource1);
assertNotNull(saxSourceReq1);
disp.invokeOneWay(saxSourceReq1);
InputStream is2=getClass().getResourceAsStream("resources/GreetMeDocLiteralSOAPBodyReq2.xml");
InputSource inputSource2=new InputSource(is2);
inputSource2.setPublicId(getClass().getResource("resources/GreetMeDocLiteralSOAPBodyReq2.xml").toString());
inputSource2.setSystemId(inputSource2.getPublicId());
SAXSource saxSourceReq2=new SAXSource(inputSource2);
assertNotNull(saxSourceReq2);
Response response=disp.invokeAsync(saxSourceReq2);
SAXSource saxSourceResp2=response.get();
assertNotNull(saxSourceResp2);
String expected2="Hello TestSOAPInputMessage2";
assertTrue("Expected: " + expected,StaxUtils.toString(saxSourceResp2).contains(expected2));
InputStream is3=getClass().getResourceAsStream("resources/GreetMeDocLiteralSOAPBodyReq3.xml");
InputSource inputSource3=new InputSource(is3);
inputSource3.setPublicId(getClass().getResource("resources/GreetMeDocLiteralSOAPBodyReq3.xml").toString());
inputSource3.setSystemId(inputSource3.getPublicId());
SAXSource saxSourceReq3=new SAXSource(inputSource3);
assertNotNull(saxSourceReq3);
TestSAXSourceHandler tssh=new TestSAXSourceHandler();
Future> fd=disp.invokeAsync(saxSourceReq3,tssh);
assertNotNull(fd);
waitForFuture(fd);
String expected3="Hello TestSOAPInputMessage3";
SAXSource saxSourceResp3=tssh.getSAXSource();
assertNotNull(saxSourceResp3);
assertTrue("Expected: " + expected,StaxUtils.toString(saxSourceResp3).contains(expected3));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testStreamSourcePAYLOAD() throws Exception {
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
SOAPService service=new SOAPService(wsdl,SERVICE_NAME);
assertNotNull(service);
Dispatch disp=service.createDispatch(PORT_NAME,StreamSource.class,Service.Mode.PAYLOAD);
disp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"http://localhost:" + greeterPort + "/SOAPDispatchService/SoapDispatchPort");
InputStream is=getClass().getResourceAsStream("resources/GreetMeDocLiteralSOAPBodyReq.xml");
StreamSource streamSourceReq=new StreamSource(is);
assertNotNull(streamSourceReq);
StreamSource streamSourceResp=disp.invoke(streamSourceReq);
assertNotNull(streamSourceResp);
String expected="Hello TestSOAPInputMessage";
assertTrue("Expected: " + expected,StaxUtils.toString(streamSourceResp).contains(expected));
InputStream is1=getClass().getResourceAsStream("resources/GreetMeDocLiteralSOAPBodyReq1.xml");
StreamSource streamSourceReq1=new StreamSource(is1);
assertNotNull(streamSourceReq1);
disp.invokeOneWay(streamSourceReq1);
InputStream is2=getClass().getResourceAsStream("resources/GreetMeDocLiteralSOAPBodyReq2.xml");
StreamSource streamSourceReq2=new StreamSource(is2);
assertNotNull(streamSourceReq2);
Response response=disp.invokeAsync(streamSourceReq2);
StreamSource streamSourceResp2=response.get();
assertNotNull(streamSourceResp2);
String expected2="Hello TestSOAPInputMessage2";
assertTrue("Expected: " + expected,StaxUtils.toString(streamSourceResp2).contains(expected2));
InputStream is3=getClass().getResourceAsStream("resources/GreetMeDocLiteralSOAPBodyReq3.xml");
StreamSource streamSourceReq3=new StreamSource(is3);
assertNotNull(streamSourceReq3);
TestStreamSourceHandler tssh=new TestStreamSourceHandler();
Future> fd=disp.invokeAsync(streamSourceReq3,tssh);
assertNotNull(fd);
waitForFuture(fd);
String expected3="Hello TestSOAPInputMessage3";
StreamSource streamSourceResp3=tssh.getStreamSource();
assertNotNull(streamSourceResp3);
assertTrue("Expected: " + expected,StaxUtils.toString(streamSourceResp3).contains(expected3));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCreateDispatchWithEPR() throws Exception {
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
SOAPService service=new SOAPService(wsdl,SERVICE_NAME);
assertNotNull(service);
W3CEndpointReferenceBuilder builder=new W3CEndpointReferenceBuilder();
builder.address("http://localhost:" + greeterPort + "/SOAPDispatchService/SoapDispatchPort");
builder.serviceName(SERVICE_NAME);
builder.endpointName(PORT_NAME);
W3CEndpointReference w3cEpr=builder.build();
Dispatch disp=service.createDispatch(w3cEpr,SOAPMessage.class,Service.Mode.MESSAGE);
InputStream is=getClass().getResourceAsStream("resources/GreetMeDocLiteralReq.xml");
SOAPMessage soapReqMsg=MessageFactory.newInstance().createMessage(null,is);
assertNotNull(soapReqMsg);
SOAPMessage soapResMsg=disp.invoke(soapReqMsg);
assertNotNull(soapResMsg);
String expected="Hello TestSOAPInputMessage";
assertEquals("Response should be : Hello TestSOAPInputMessage",expected,DOMUtils.getAllContent(SAAJUtils.getBody(soapResMsg)).trim());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSOAPMessage() throws Exception {
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
SOAPService service=new SOAPService(wsdl,SERVICE_NAME);
assertNotNull(service);
Dispatch disp=service.createDispatch(PORT_NAME,SOAPMessage.class,Service.Mode.MESSAGE);
disp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"http://localhost:" + greeterPort + "/SOAPDispatchService/SoapDispatchPort");
InputStream is=getClass().getResourceAsStream("resources/GreetMeDocLiteralReq.xml");
SOAPMessage soapReqMsg=MessageFactory.newInstance().createMessage(null,is);
assertNotNull(soapReqMsg);
SOAPMessage soapResMsg=disp.invoke(soapReqMsg);
assertNotNull(soapResMsg);
String expected="Hello TestSOAPInputMessage";
assertEquals("Response should be : Hello TestSOAPInputMessage",expected,DOMUtils.getContent(SAAJUtils.getBody(soapResMsg).getFirstChild().getFirstChild()).trim());
InputStream is1=getClass().getResourceAsStream("resources/GreetMe1WDocLiteralReq2.xml");
SOAPMessage soapReqMsg1=MessageFactory.newInstance().createMessage(null,is1);
assertNotNull(soapReqMsg1);
disp.invokeOneWay(soapReqMsg1);
InputStream is2=getClass().getResourceAsStream("resources/GreetMeDocLiteralReq2.xml");
SOAPMessage soapReqMsg2=MessageFactory.newInstance().createMessage(null,is2);
assertNotNull(soapReqMsg2);
Response> response=disp.invokeAsync(soapReqMsg2);
SOAPMessage soapResMsg2=(SOAPMessage)response.get();
assertNotNull(soapResMsg2);
String expected2="Hello TestSOAPInputMessage2";
assertEquals("Response should be : Hello TestSOAPInputMessage2",expected2,DOMUtils.getContent(SAAJUtils.getBody(soapResMsg2).getFirstChild().getFirstChild()));
InputStream is3=getClass().getResourceAsStream("resources/GreetMeDocLiteralReq3.xml");
SOAPMessage soapReqMsg3=MessageFactory.newInstance().createMessage(null,is3);
assertNotNull(soapReqMsg3);
TestSOAPMessageHandler tsmh=new TestSOAPMessageHandler();
Future> f=disp.invokeAsync(soapReqMsg3,tsmh);
assertNotNull(f);
waitForFuture(f);
String expected3="Hello TestSOAPInputMessage3";
assertEquals("Response should be : Hello TestSOAPInputMessage3",expected3,tsmh.getReplyBuffer().trim());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testSAXSourceMESSAGE() throws Exception {
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
SOAPService service=new SOAPService(wsdl,SERVICE_NAME);
assertNotNull(service);
InputStream is=getClass().getResourceAsStream("resources/GreetMeDocLiteralReq.xml");
InputSource inputSource=new InputSource(is);
SAXSource saxSourceReq=new SAXSource(inputSource);
assertNotNull(saxSourceReq);
Dispatch disp=service.createDispatch(PORT_NAME,SAXSource.class,Service.Mode.MESSAGE);
disp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"http://localhost:" + greeterPort + "/SOAPDispatchService/SoapDispatchPort");
SAXSource saxSourceResp=disp.invoke(saxSourceReq);
assertNotNull(saxSourceResp);
String expected="Hello TestSOAPInputMessage";
assertTrue("Expected: " + expected,StaxUtils.toString(saxSourceResp).contains(expected));
InputStream is1=getClass().getResourceAsStream("resources/GreetMeDocLiteralReq1.xml");
InputSource inputSource1=new InputSource(is1);
SAXSource saxSourceReq1=new SAXSource(inputSource1);
assertNotNull(saxSourceReq1);
disp.invokeOneWay(saxSourceReq1);
InputStream is2=getClass().getResourceAsStream("resources/GreetMeDocLiteralReq2.xml");
InputSource inputSource2=new InputSource(is2);
SAXSource saxSourceReq2=new SAXSource(inputSource2);
assertNotNull(saxSourceReq2);
Response response=disp.invokeAsync(saxSourceReq2);
SAXSource saxSourceResp2=response.get();
assertNotNull(saxSourceResp2);
String expected2="Hello TestSOAPInputMessage2";
assertTrue("Expected: " + expected,StaxUtils.toString(saxSourceResp2).contains(expected2));
InputStream is3=getClass().getResourceAsStream("resources/GreetMeDocLiteralReq3.xml");
InputSource inputSource3=new InputSource(is3);
SAXSource saxSourceReq3=new SAXSource(inputSource3);
assertNotNull(saxSourceReq3);
TestSAXSourceHandler tssh=new TestSAXSourceHandler();
Future> fd=disp.invokeAsync(saxSourceReq3,tssh);
assertNotNull(fd);
waitForFuture(fd);
String expected3="Hello TestSOAPInputMessage3";
SAXSource saxSourceResp3=tssh.getSAXSource();
assertNotNull(saxSourceResp3);
assertTrue("Expected: " + expected,StaxUtils.toString(saxSourceResp3).contains(expected3));
}
APIUtilityVerifier UtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testSAXSourceMESSAGEWithSchemaValidation() throws Exception {
URL wsdl=getClass().getResource("/org/apache/cxf/systest/provider/hello_world_with_restriction.wsdl");
assertNotNull(wsdl);
SOAPService service=new SOAPService(wsdl,SERVICE_NAME);
assertNotNull(service);
InputStream is=getClass().getResourceAsStream("resources/GreetMeDocLiteralReq.xml");
InputSource inputSource=new InputSource(is);
SAXSource saxSourceReq=new SAXSource(inputSource);
assertNotNull(saxSourceReq);
Dispatch disp=service.createDispatch(PORT_NAME,SAXSource.class,Service.Mode.MESSAGE);
disp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"http://localhost:" + greeterPort + "/SOAPDispatchService/SoapDispatchPort");
disp.getRequestContext().put(Message.SCHEMA_VALIDATION_ENABLED,Boolean.TRUE);
SAXSource saxSourceResp=disp.invoke(saxSourceReq);
assertNotNull(saxSourceResp);
String expected="Hello TestSOAPInputMessage";
assertTrue("Expected: " + expected,StaxUtils.toString(saxSourceResp).contains(expected));
is=getClass().getResourceAsStream("resources/GreetMeDocLiteralReqWithExceedMaxLength.xml");
inputSource=new InputSource(is);
saxSourceReq=new SAXSource(inputSource);
assertNotNull(saxSourceReq);
try {
disp.invoke(saxSourceReq);
fail("Should have thrown an exception");
}
catch ( Exception ex) {
assertTrue(ex.getMessage().contains("cvc-maxLength-valid"));
}
}
APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testSOAPMessageInvokeToOneWay() throws Exception {
SOAPService service=new SOAPService(null,SERVICE_NAME);
service.addPort(PORT_NAME,SOAPBinding.SOAP11HTTP_BINDING,"http://localhost:" + greeterPort + "/SOAPDispatchService/SoapDispatchPort");
assertNotNull(service);
Dispatch disp=service.createDispatch(PORT_NAME,SOAPMessage.class,Service.Mode.MESSAGE);
InputStream is1=getClass().getResourceAsStream("resources/GreetMe1WDocLiteralReq2.xml");
SOAPMessage soapReqMsg1=MessageFactory.newInstance().createMessage(null,is1);
assertNotNull(soapReqMsg1);
disp.invoke(soapReqMsg1);
AsyncHandler callback=new AsyncHandler(){
public void handleResponse( Response res){
synchronized (this) {
notifyAll();
}
}
}
;
synchronized (callback) {
disp.invokeAsync(soapReqMsg1,callback);
callback.wait();
}
}
Class: org.apache.cxf.systest.dispatch.DispatchClientServerWithHugeResponseTest APIUtilityVerifier UtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testThresholdfForSOAPMessageWithHugeResponse() throws Exception {
HugeResponseInterceptor hugeResponseInterceptor=new HugeResponseInterceptor(ResponseInterceptorType.ElementLevelThreshold);
getBus().getInInterceptors().add(hugeResponseInterceptor);
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
SOAPService service=new SOAPService(wsdl,SERVICE_NAME);
assertNotNull(service);
Dispatch disp=service.createDispatch(PORT_NAME,SOAPMessage.class,Service.Mode.MESSAGE);
disp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"http://localhost:" + greeterPort + "/SOAPDispatchService/SoapDispatchPort");
StaxUtils.setInnerElementCountThreshold(12);
StaxUtils.setInnerElementLevelThreshold(12);
InputStream is3=getClass().getResourceAsStream("resources/GreetMeDocLiteralReq3.xml");
SOAPMessage soapReqMsg3=MessageFactory.newInstance().createMessage(null,is3);
assertNotNull(soapReqMsg3);
Response response=disp.invokeAsync(soapReqMsg3);
try {
response.get(300,TimeUnit.SECONDS);
}
catch ( TimeoutException te) {
fail("We should not have encountered a timeout, " + "should get some exception tell me stackoverflow");
}
catch ( Throwable e) {
if (e.getCause() == null) {
throw e;
}
Throwable t=e.getCause();
if (t instanceof SoapFault) {
SoapFault sf=(SoapFault)e.getCause();
if (sf.getCause() == null) {
throw e;
}
t=sf.getCause();
}
if (t.getMessage() == null) {
throw e;
}
String msg=t.getMessage();
assertTrue(msg,msg.startsWith("reach the innerElementLevelThreshold") || msg.contains("Maximum Element Depth limit"));
}
finally {
getBus().getInInterceptors().remove(hugeResponseInterceptor);
}
}
APIUtilityVerifier UtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testElementCountThresholdfForSOAPMessageWithHugeResponse() throws Throwable {
HugeResponseInterceptor hugeResponseInterceptor=new HugeResponseInterceptor(ResponseInterceptorType.ElementCountThreshold);
getBus().getInInterceptors().add(hugeResponseInterceptor);
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
SOAPService service=new SOAPService(wsdl,SERVICE_NAME);
assertNotNull(service);
Dispatch disp=service.createDispatch(PORT_NAME,SOAPMessage.class,Service.Mode.MESSAGE);
disp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"http://localhost:" + greeterPort + "/SOAPDispatchService/SoapDispatchPort");
StaxUtils.setInnerElementCountThreshold(12);
StaxUtils.setInnerElementLevelThreshold(12);
InputStream is3=getClass().getResourceAsStream("resources/GreetMeDocLiteralReq3.xml");
SOAPMessage soapReqMsg3=MessageFactory.newInstance().createMessage(null,is3);
assertNotNull(soapReqMsg3);
Response response=disp.invokeAsync(soapReqMsg3);
try {
response.get(300,TimeUnit.SECONDS);
fail("should catch exception");
}
catch ( TimeoutException te) {
fail("We should not have encountered a timeout, " + "should get some exception tell me stackoverflow");
}
catch ( ExecutionException e) {
if (e.getCause() == null) {
throw e;
}
Throwable t=e.getCause();
if (t instanceof SoapFault) {
SoapFault sf=(SoapFault)e.getCause();
if (sf.getCause() == null) {
throw e;
}
t=sf.getCause();
}
if (t.getMessage() == null) {
throw e;
}
String msg=t.getMessage();
assertTrue(msg,msg.startsWith("reach the innerElementCountThreshold") || msg.contains("Maximum Number of Child Elements"));
}
finally {
getBus().getInInterceptors().remove(hugeResponseInterceptor);
}
}
Class: org.apache.cxf.systest.dispatch.DispatchClientServerWithMalformedResponseTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSOAPMessageWithMalformedResponse() throws Exception {
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
SOAPService service=new SOAPService(wsdl,SERVICE_NAME);
assertNotNull(service);
Dispatch disp=service.createDispatch(PORT_NAME,SOAPMessage.class,Service.Mode.MESSAGE);
disp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"http://localhost:" + greeterPort + "/SOAPDispatchService/SoapDispatchPort");
InputStream is3=getClass().getResourceAsStream("resources/GreetMeDocLiteralReq3.xml");
SOAPMessage soapReqMsg3=MessageFactory.newInstance().createMessage(null,is3);
assertNotNull(soapReqMsg3);
TestSOAPMessageHandler tsmh=new TestSOAPMessageHandler();
Future> f=disp.invokeAsync(soapReqMsg3,tsmh);
assertNotNull(f);
waitForFuture(f);
assertEquals("AsyncHandler shouldn't get invoked more than once",asyncHandlerInvokedCount,1);
}
Class: org.apache.cxf.systest.dispatch.DispatchXMLClientServerTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testStreamSourceMESSAGE() throws Exception {
Service service=Service.create(SERVICE_NAME);
assertNotNull(service);
service.addPort(PORT_NAME,"http://cxf.apache.org/bindings/xformat","http://localhost:" + port + "/XMLService/XMLDispatchPort");
InputStream is=getClass().getResourceAsStream("/messages/XML_GreetMeDocLiteralReq.xml");
StreamSource reqMsg=new StreamSource(is);
assertNotNull(reqMsg);
Dispatch disp=service.createDispatch(PORT_NAME,Source.class,Service.Mode.MESSAGE);
Source source=disp.invoke(reqMsg);
assertNotNull(source);
String streamString=StaxUtils.toString(source);
Document doc=StaxUtils.read(new StringReader(streamString));
assertEquals("greetMeResponse",doc.getFirstChild().getLocalName());
assertEquals("Hello tli",doc.getFirstChild().getTextContent());
}
APIUtilityVerifier UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testJAXBMESSAGE() throws Exception {
Service service=Service.create(SERVICE_NAME);
assertNotNull(service);
service.addPort(PORT_NAME,"http://cxf.apache.org/bindings/xformat","http://localhost:" + port + "/XMLService/XMLDispatchPort");
GreetMe gm=new GreetMe();
gm.setRequestType("CXF");
JAXBContext ctx=JAXBContext.newInstance(ObjectFactory.class);
Dispatch disp=service.createDispatch(PORT_NAME,ctx,Service.Mode.MESSAGE);
GreetMeResponse resp=(GreetMeResponse)disp.invoke(gm);
assertNotNull(resp);
assertEquals("Hello CXF",resp.getResponseType());
try {
disp.invoke(null);
fail("Should have thrown a fault");
}
catch ( WebServiceException ex) {
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testDOMSourcePAYLOAD() throws Exception {
URL wsdl=getClass().getResource("/wsdl/hello_world_xml_wrapped.wsdl");
assertNotNull(wsdl);
XMLService service=new XMLService(wsdl,SERVICE_NAME);
assertNotNull(service);
InputStream is=getClass().getResourceAsStream("/messages/XML_GreetMeDocLiteralReq.xml");
Document doc=StaxUtils.read(is);
DOMSource reqMsg=new DOMSource(doc);
assertNotNull(reqMsg);
Dispatch disp=service.createDispatch(PORT_NAME,DOMSource.class,Service.Mode.PAYLOAD);
disp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"http://localhost:" + port + "/XMLService/XMLDispatchPort");
DOMSource result=disp.invoke(reqMsg);
assertNotNull(result);
Node respDoc=result.getNode();
assertEquals("greetMeResponse",respDoc.getFirstChild().getLocalName());
assertEquals("Hello tli",respDoc.getFirstChild().getTextContent());
}
Class: org.apache.cxf.systest.exception.GenericExceptionTest APIUtilityVerifier UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGenericException() throws Exception {
String address="http://localhost:" + PORT + "/generic";
URL wsdlURL=new URL(address + "?wsdl");
InputStream ins=wsdlURL.openStream();
Document doc=StaxUtils.read(ins);
Map ns=new HashMap();
ns.put("xsd","http://www.w3.org/2001/XMLSchema");
ns.put("wsdl","http://schemas.xmlsoap.org/wsdl/");
ns.put("tns","http://cxf.apache.org/test/HelloService");
XPathUtils xpu=new XPathUtils(ns);
Node nd=xpu.getValueNode("//xsd:complexType[@name='objectWithGenerics']",doc);
assertNotNull(nd);
assertNotNull(xpu.getValueNode("//xsd:element[@name='a']",nd));
assertNotNull(xpu.getValueNode("//xsd:element[@name='b']",nd));
Service service=Service.create(wsdlURL,serviceName);
service.addPort(new QName("http://cxf.apache.org/test/HelloService","HelloPort"),SOAPBinding.SOAP11HTTP_BINDING,address);
GenericsEcho port=service.getPort(new QName("http://cxf.apache.org/test/HelloService","HelloPort"),GenericsEcho.class);
try {
port.echo("test");
fail("Exception is expected");
}
catch ( GenericsException e) {
ObjectWithGenerics genericObj=e.getObj();
assertEquals(true,genericObj.getA());
assertEquals(100,genericObj.getB().intValue());
}
}
Class: org.apache.cxf.systest.factory_pattern.ManualHttpMulitplexClientServerTest APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testWithGetPortExtensionHttp() throws Exception {
NumberFactoryService service=new NumberFactoryService();
NumberFactory factory=service.getNumberFactoryPort();
updateAddressPort(factory,PORT);
W3CEndpointReference w3cEpr=factory.create("20");
EndpointReferenceType numberTwoRef=ProviderImpl.convertToInternal(w3cEpr);
assertNotNull("reference",numberTwoRef);
NumberService numService=new NumberService();
ServiceImpl serviceImpl=ServiceDelegateAccessor.get(numService);
Number num=serviceImpl.getPort(numberTwoRef,Number.class);
assertTrue("20 is even",num.isEven().isEven());
w3cEpr=factory.create("23");
EndpointReferenceType numberTwentyThreeRef=ProviderImpl.convertToInternal(w3cEpr);
num=serviceImpl.getPort(numberTwentyThreeRef,Number.class);
assertTrue("23 is not even",!num.isEven().isEven());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testWithManualMultiplexEprCreation() throws Exception {
NumberFactoryService service=new NumberFactoryService();
NumberFactory nfact=service.getNumberFactoryPort();
updateAddressPort(nfact,PORT);
W3CEndpointReference w3cEpr=nfact.create("2");
assertNotNull("reference",w3cEpr);
EndpointReferenceType epr=ProviderImpl.convertToInternal(w3cEpr);
QName serviceName=EndpointReferenceUtils.getServiceName(epr,bus);
Service numService=Service.create(serviceName);
String portString=EndpointReferenceUtils.getPortName(epr);
QName portName=new QName(serviceName.getNamespaceURI(),portString);
numService.addPort(portName,SoapBindingFactory.SOAP_11_BINDING,"http://foo");
Number num=numService.getPort(portName,Number.class);
setupContextWithEprAddress(epr,num);
IsEvenResponse numResp=num.isEven();
assertTrue("2 is even",Boolean.TRUE.equals(numResp.isEven()));
w3cEpr=nfact.create("3");
epr=ProviderImpl.convertToInternal(w3cEpr);
setupContextWithEprAddress(epr,num);
numResp=num.isEven();
assertTrue("3 is not even",Boolean.FALSE.equals(numResp.isEven()));
w3cEpr=nfact.create("6");
epr=ProviderImpl.convertToInternal(w3cEpr);
setupContextWithEprAddress(epr,num);
numResp=num.isEven();
assertTrue("6 is even",Boolean.TRUE.equals(numResp.isEven()));
}
Class: org.apache.cxf.systest.factory_pattern.MultiplexClientServerTest APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testWithGetPortExtensionHttp() throws Exception {
NumberFactoryService service=new NumberFactoryService();
NumberFactory factory=service.getNumberFactoryPort();
updateAddressPort(factory,PORT);
NumberService numService=new NumberService();
ServiceImpl serviceImpl=ServiceDelegateAccessor.get(numService);
W3CEndpointReference numberTwoRef=factory.create("20");
assertNotNull("reference",numberTwoRef);
Number num=serviceImpl.getPort(numberTwoRef,Number.class);
assertTrue("20 is even",num.isEven().isEven());
close(num);
W3CEndpointReference numberTwentyThreeRef=factory.create("23");
num=serviceImpl.getPort(numberTwentyThreeRef,Number.class);
assertTrue("23 is not even",!num.isEven().isEven());
close(num);
close(factory);
}
APIUtilityVerifier UtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testWithGetPortExtensionOverJMS() throws Exception {
NumberFactoryService service=new NumberFactoryService();
NumberFactory factory=service.getNumberFactoryPort();
updateAddressPort(factory,PORT);
W3CEndpointReference ref=factory.create("999");
String s=NumberService.WSDL_LOCATION.toString();
EmbeddedJMSBrokerLauncher.updateWsdlExtensors(BusFactory.getDefaultBus(),s);
NumberService numService=new NumberService();
assertNotNull("reference",ref);
ServiceImpl serviceImpl=ServiceDelegateAccessor.get(numService);
Number num=serviceImpl.getPort(ref,Number.class);
try {
num.isEven().isEven();
fail("there should be a fault on val 999");
}
catch ( Exception expected) {
assertTrue("match on exception message " + expected.getMessage(),expected.getMessage().indexOf("999") != -1);
}
ClientProxy.getClient(num).getConduit().close();
ref=factory.create("37");
assertNotNull("reference",ref);
num=serviceImpl.getPort(ref,Number.class);
assertTrue("37 is not even",!num.isEven().isEven());
ClientProxy.getClient(num).getConduit().close();
ClientProxy.getClient(factory).getConduit().close();
}
Class: org.apache.cxf.systest.factory_pattern.MultiplexHttpAddressClientServerTest APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testWithGetPortExtensionHttp() throws Exception {
NumberFactoryService service=new NumberFactoryService();
NumberFactory factory=service.getNumberFactoryPort();
updateAddressPort(factory,PORT);
NumberService numService=new NumberService();
ServiceImpl serviceImpl=ServiceDelegateAccessor.get(numService);
W3CEndpointReference numberTwoRef=factory.create("20");
assertNotNull("reference",numberTwoRef);
Number num=serviceImpl.getPort(numberTwoRef,Number.class);
assertTrue("20 is even",num.isEven().isEven());
W3CEndpointReference numberTwentyThreeRef=factory.create("23");
num=serviceImpl.getPort(numberTwentyThreeRef,Number.class);
assertTrue("23 is not even",!num.isEven().isEven());
}
Class: org.apache.cxf.systest.handlers.DispatchHandlerInvocationTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testInvokeWithJAXBMessageModeXMLBinding() throws Exception {
URL wsdl=getClass().getResource("/wsdl/addNumbers.wsdl");
assertNotNull(wsdl);
XMLService service=new XMLService();
assertNotNull(service);
JAXBContext jc=JAXBContext.newInstance("org.apache.hello_world_xml_http.wrapped.types");
Dispatch disp=service.createDispatch(portNameXML,jc,Mode.MESSAGE);
setAddress(disp,greeterAddress);
TestHandlerXMLBinding handler=new TestHandlerXMLBinding();
addHandlersProgrammatically(disp,handler);
org.apache.hello_world_xml_http.wrapped.types.GreetMe req=new org.apache.hello_world_xml_http.wrapped.types.GreetMe();
req.setRequestType("tli");
Object response=disp.invoke(req);
assertNotNull(response);
org.apache.hello_world_xml_http.wrapped.types.GreetMeResponse value=(org.apache.hello_world_xml_http.wrapped.types.GreetMeResponse)response;
assertEquals("Hello tli",value.getResponseType());
}
APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testInvokeWithDOMSourcPayloadMode() throws Exception {
URL wsdl=getClass().getResource("/wsdl/addNumbers.wsdl");
assertNotNull(wsdl);
AddNumbersService service=new AddNumbersService(wsdl,serviceName);
assertNotNull(service);
Dispatch disp=service.createDispatch(portName,DOMSource.class,Mode.PAYLOAD);
setAddress(disp,addNumbersAddress);
TestHandler handler=new TestHandler();
TestSOAPHandler soapHandler=new TestSOAPHandler();
addHandlersProgrammatically(disp,handler,soapHandler);
InputStream is2=this.getClass().getResourceAsStream("resources/GreetMeDocLiteralReqPayload.xml");
MessageFactory factory=MessageFactory.newInstance();
SOAPMessage soapReq=factory.createMessage(null,is2);
DOMSource domReqMessage=new DOMSource(soapReq.getSOAPPart());
DOMSource response=disp.invoke(domReqMessage);
assertNotNull(response);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testInvokeWithJAXBPayloadModeXMLBinding() throws Exception {
URL wsdl=getClass().getResource("/wsdl/addNumbers.wsdl");
assertNotNull(wsdl);
XMLService service=new XMLService();
assertNotNull(service);
JAXBContext jc=JAXBContext.newInstance("org.apache.hello_world_xml_http.wrapped.types");
Dispatch disp=service.createDispatch(portNameXML,jc,Mode.PAYLOAD);
setAddress(disp,greeterAddress);
TestHandlerXMLBinding handler=new TestHandlerXMLBinding();
addHandlersProgrammatically(disp,handler);
org.apache.hello_world_xml_http.wrapped.types.GreetMe req=new org.apache.hello_world_xml_http.wrapped.types.GreetMe();
req.setRequestType("tli");
Object response=disp.invoke(req);
assertNotNull(response);
org.apache.hello_world_xml_http.wrapped.types.GreetMeResponse value=(org.apache.hello_world_xml_http.wrapped.types.GreetMeResponse)response;
assertEquals("Hello tli",value.getResponseType());
}
APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testInvokeWithDOMSourcMessageMode() throws Exception {
URL wsdl=getClass().getResource("/wsdl/addNumbers.wsdl");
assertNotNull(wsdl);
AddNumbersService service=new AddNumbersService(wsdl,serviceName);
assertNotNull(service);
Dispatch disp=service.createDispatch(portName,DOMSource.class,Mode.MESSAGE);
setAddress(disp,addNumbersAddress);
TestHandler handler=new TestHandler();
TestSOAPHandler soapHandler=new TestSOAPHandler();
addHandlersProgrammatically(disp,handler,soapHandler);
InputStream is=this.getClass().getResourceAsStream("resources/GreetMeDocLiteralReq.xml");
MessageFactory factory=MessageFactory.newInstance();
SOAPMessage soapReq=factory.createMessage(null,is);
soapReq.saveChanges();
DOMSource domReqMessage=new DOMSource(soapReq.getSOAPPart());
DOMSource response=disp.invoke(domReqMessage);
assertNotNull(response);
}
APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testInvokeWithSOAPMessageMessageMode() throws Exception {
URL wsdl=getClass().getResource("/wsdl/addNumbers.wsdl");
assertNotNull(wsdl);
AddNumbersService service=new AddNumbersService(wsdl,serviceName);
assertNotNull(service);
Dispatch disp=service.createDispatch(portName,SOAPMessage.class,Mode.MESSAGE);
setAddress(disp,addNumbersAddress);
TestHandler handler=new TestHandler();
TestSOAPHandler soapHandler=new TestSOAPHandler();
addHandlersProgrammatically(disp,handler,soapHandler);
InputStream is2=this.getClass().getResourceAsStream("resources/GreetMeDocLiteralReq.xml");
MessageFactory factory=MessageFactory.newInstance();
SOAPMessage soapReq=factory.createMessage(null,is2);
SOAPMessage response=disp.invoke(soapReq);
assertNotNull(response);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testInvokeWithJAXBUnwrapPayloadMode() throws Exception {
URL wsdl=getClass().getResource("/wsdl/addNumbers.wsdl");
assertNotNull(wsdl);
org.apache.cxf.systest.handlers.AddNumbersServiceUnwrap service=new org.apache.cxf.systest.handlers.AddNumbersServiceUnwrap(wsdl,serviceName);
assertNotNull(service);
JAXBContext jc=JAXBContext.newInstance(org.apache.cxf.systest.handlers.types.AddNumbers.class,org.apache.cxf.systest.handlers.types.AddNumbersResponse.class);
Dispatch disp=service.createDispatch(portName,jc,Service.Mode.PAYLOAD);
setAddress(disp,addNumbersAddress);
TestHandler handler=new TestHandler();
TestSOAPHandler soapHandler=new TestSOAPHandler();
addHandlersProgrammatically(disp,handler,soapHandler);
org.apache.cxf.systest.handlers.types.AddNumbers req=new org.apache.cxf.systest.handlers.types.AddNumbers();
req.setArg0(10);
req.setArg1(20);
org.apache.cxf.systest.handlers.types.AddNumbersResponse response=(org.apache.cxf.systest.handlers.types.AddNumbersResponse)disp.invoke(req);
assertNotNull(response);
assertEquals(222,response.getReturn());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testInvokeWithJAXBPayloadMode() throws Exception {
URL wsdl=getClass().getResource("/wsdl/addNumbers.wsdl");
assertNotNull(wsdl);
AddNumbersService service=new AddNumbersService(wsdl,serviceName);
assertNotNull(service);
JAXBContext jc=JAXBContext.newInstance("org.apache.handlers.types");
Dispatch disp=service.createDispatch(portName,jc,Service.Mode.PAYLOAD);
setAddress(disp,addNumbersAddress);
TestHandler handler=new TestHandler();
TestSOAPHandler soapHandler=new TestSOAPHandler();
addHandlersProgrammatically(disp,handler,soapHandler);
org.apache.handlers.types.AddNumbers req=new org.apache.handlers.types.AddNumbers();
req.setArg0(10);
req.setArg1(20);
ObjectFactory factory=new ObjectFactory();
JAXBElement e=factory.createAddNumbers(req);
JAXBElement> response=(JAXBElement>)disp.invoke(e);
assertNotNull(response);
AddNumbersResponse value=(AddNumbersResponse)response.getValue();
assertEquals(222,value.getReturn());
}
APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testInvokeWithDOMSourcMessageModeXMLBinding() throws Exception {
URL wsdl=getClass().getResource("/wsdl/addNumbers.wsdl");
assertNotNull(wsdl);
XMLService service=new XMLService();
assertNotNull(service);
Dispatch disp=service.createDispatch(portNameXML,DOMSource.class,Mode.MESSAGE);
setAddress(disp,addNumbersAddress);
TestHandlerXMLBinding handler=new TestHandlerXMLBinding();
addHandlersProgrammatically(disp,handler);
InputStream is=getClass().getResourceAsStream("/messages/XML_GreetMeDocLiteralReq.xml");
MessageFactory factory=MessageFactory.newInstance();
SOAPMessage soapReq=factory.createMessage(null,is);
DOMSource domReqMessage=new DOMSource(soapReq.getSOAPPart());
DOMSource response=disp.invoke(domReqMessage);
assertNotNull(response);
}
APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testInvokeWithDOMSourcPayloadModeXMLBinding() throws Exception {
URL wsdl=getClass().getResource("/wsdl/addNumbers.wsdl");
assertNotNull(wsdl);
XMLService service=new XMLService();
assertNotNull(service);
Dispatch disp=service.createDispatch(portNameXML,DOMSource.class,Mode.PAYLOAD);
setAddress(disp,addNumbersAddress);
TestHandlerXMLBinding handler=new TestHandlerXMLBinding();
addHandlersProgrammatically(disp,handler);
InputStream is=getClass().getResourceAsStream("/messages/XML_GreetMeDocLiteralReq.xml");
MessageFactory factory=MessageFactory.newInstance();
SOAPMessage soapReq=factory.createMessage(null,is);
DOMSource domReqMessage=new DOMSource(soapReq.getSOAPPart());
DOMSource response=disp.invoke(domReqMessage);
assertNotNull(response);
}
Class: org.apache.cxf.systest.handlers.HandlerInvocationTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testSOAPHandlerHandleMessageReturnFalseClientInbound() throws Exception {
TestHandler handler1=new TestHandler(false);
TestHandler handler2=new TestHandler(false);
TestSOAPHandler soapHandler1=new TestSOAPHandler(false);
TestSOAPHandler soapHandler2=new TestSOAPHandler(false){
public boolean handleMessage( SOAPMessageContext ctx){
super.handleMessage(ctx);
Boolean outbound=(Boolean)ctx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (!outbound) {
return false;
}
return true;
}
}
;
addHandlersToChain((BindingProvider)handlerTest,handler1,handler2,soapHandler1,soapHandler2);
handlerTest.ping();
assertEquals(1,handler1.getHandleMessageInvoked());
assertEquals(1,handler2.getHandleMessageInvoked());
assertEquals(1,soapHandler1.getHandleMessageInvoked());
assertEquals(2,soapHandler2.getHandleMessageInvoked());
assertEquals("close must be called",1,handler1.getCloseInvoked());
assertEquals("close must be called",1,handler2.getCloseInvoked());
assertEquals("close must be called",1,soapHandler1.getCloseInvoked());
assertEquals("close must be called",1,soapHandler2.getCloseInvoked());
assertTrue(soapHandler2.getInvokeOrderOfClose() < soapHandler1.getInvokeOrderOfClose());
assertTrue(soapHandler1.getInvokeOrderOfClose() < handler2.getInvokeOrderOfClose());
assertTrue(handler2.getInvokeOrderOfClose() < handler1.getInvokeOrderOfClose());
}
InternalCallVerifier EqualityVerifier
@Test public void testLogicHandlerHandleMessageReturnFalseServerOutbound() throws PingException {
String[] expectedHandlers={"server handler1 outbound stop","soapHandler4","soapHandler3","handler2","handler1","handler1"};
List resp=handlerTest.pingWithArgs("server handler1 outbound stop");
assertEquals(expectedHandlers.length,resp.size());
int i=0;
for ( String expected : expectedHandlers) {
assertEquals(expected,resp.get(i++));
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testDescription() throws PingException {
TestHandler handler=new TestHandler(false){
public boolean handleMessage( LogicalMessageContext ctx){
super.handleMessage(ctx);
assertTrue("wsdl description not found or invalid",isValidWsdlDescription(ctx.get(MessageContext.WSDL_DESCRIPTION)));
return true;
}
}
;
TestSOAPHandler soapHandler=new TestSOAPHandler(false){
public boolean handleMessage( SOAPMessageContext ctx){
super.handleMessage(ctx);
assertTrue("wsdl description not found or invalid",isValidWsdlDescription(ctx.get(MessageContext.WSDL_DESCRIPTION)));
return true;
}
}
;
addHandlersToChain((BindingProvider)handlerTest,handler,soapHandler);
List resp=handlerTest.ping();
assertNotNull(resp);
assertEquals("handler was not invoked",2,handler.getHandleMessageInvoked());
assertEquals("handle message was not invoked",2,soapHandler.getHandleMessageInvoked());
assertTrue("close must be called",handler.isCloseInvoked());
assertTrue("close must be called",soapHandler.isCloseInvoked());
}
APIUtilityVerifier BranchVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSOAPHandlerHandleMessageReturnTrueClient() throws Exception {
TestHandler handler1=new TestHandler(false);
TestHandler handler2=new TestHandler(false){
public boolean handleMessage( LogicalMessageContext ctx){
super.handleMessage(ctx);
try {
Boolean outbound=(Boolean)ctx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (!outbound) {
LogicalMessage msg=ctx.getMessage();
Source source=msg.getPayload();
assertNotNull(source);
}
}
catch ( Exception e) {
e.printStackTrace();
fail(e.toString());
}
return true;
}
}
;
TestSOAPHandler soapHandler1=new TestSOAPHandler(false);
TestSOAPHandler soapHandler2=new TestSOAPHandler(false);
addHandlersToChain((BindingProvider)handlerTest,handler1,handler2,soapHandler1,soapHandler2);
List resp=handlerTest.ping();
assertNotNull(resp);
assertEquals("handle message was not invoked",2,handler1.getHandleMessageInvoked());
assertEquals("handle message was not invoked",2,handler2.getHandleMessageInvoked());
assertEquals("handle message was not invoked",2,soapHandler1.getHandleMessageInvoked());
assertEquals("handle message was not invoked",2,soapHandler2.getHandleMessageInvoked());
assertEquals("close must be called",1,handler1.getCloseInvoked());
assertEquals("close must be called",1,handler2.getCloseInvoked());
assertEquals("close must be called",1,soapHandler1.getCloseInvoked());
assertEquals("close must be called",1,soapHandler2.getCloseInvoked());
assertTrue(soapHandler2.getInvokeOrderOfClose() < soapHandler1.getInvokeOrderOfClose());
assertTrue(soapHandler1.getInvokeOrderOfClose() < handler2.getInvokeOrderOfClose());
assertTrue(handler2.getInvokeOrderOfClose() < handler1.getInvokeOrderOfClose());
String[] handlerNames={"soapHandler4","soapHandler3","handler2","handler1","servant","handler1","handler2","soapHandler3","soapHandler4"};
assertEquals(handlerNames.length,resp.size());
Iterator iter=resp.iterator();
for ( String expected : handlerNames) {
assertEquals(expected,iter.next());
}
}
APIUtilityVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testSOAPHandlerHandleMessageThrowsProtocolExceptionClientOutbound() throws Exception {
final String clientHandlerMessage="handler1 client side";
TestHandler handler1=new TestHandler(false);
TestHandler handler2=new TestHandler(false);
TestSOAPHandler soapHandler1=new TestSOAPHandler(false){
public boolean handleMessage( SOAPMessageContext ctx){
super.handleMessage(ctx);
Boolean outbound=(Boolean)ctx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outbound) {
throw new ProtocolException(clientHandlerMessage);
}
return true;
}
}
;
TestSOAPHandler soapHandler2=new TestSOAPHandler(false);
addHandlersToChain((BindingProvider)handlerTest,handler1,handler2,soapHandler1,soapHandler2);
try {
handlerTest.ping();
fail("did not get expected exception");
}
catch ( ProtocolException e) {
assertEquals(clientHandlerMessage,e.getMessage());
}
assertEquals(1,handler1.getHandleMessageInvoked());
assertEquals(1,handler2.getHandleMessageInvoked());
assertEquals(1,soapHandler1.getHandleMessageInvoked());
assertEquals(0,soapHandler2.getHandleMessageInvoked());
assertEquals(1,handler2.getHandleFaultInvoked());
assertEquals(1,handler1.getHandleFaultInvoked());
assertEquals(0,soapHandler1.getHandleFaultInvoked());
assertEquals(0,soapHandler2.getHandleFaultInvoked());
assertEquals(1,handler1.getCloseInvoked());
assertEquals(1,handler2.getCloseInvoked());
assertEquals(1,soapHandler1.getCloseInvoked());
assertEquals(0,soapHandler2.getCloseInvoked());
assertTrue(handler2.getInvokeOrderOfClose() < handler1.getInvokeOrderOfClose());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testHandlersInvokedForDispatch() throws Exception {
Dispatch disp=service.createDispatch(portName,SOAPMessage.class,Service.Mode.MESSAGE);
setAddress(disp,"http://localhost:" + port + "/HandlerTest/SoapPort");
TestHandler handler1=new TestHandler(false);
TestHandler handler2=new TestHandler(false);
TestSOAPHandler soapHandler1=new TestSOAPHandler(false);
TestSOAPHandler soapHandler2=new TestSOAPHandler(false);
addHandlersToChain(disp,handler1,handler2,soapHandler1,soapHandler2);
InputStream is=getClass().getResourceAsStream("PingReq.xml");
SOAPMessage outMsg=MessageFactory.newInstance().createMessage(null,is);
SOAPMessage inMsg=disp.invoke(outMsg);
assertNotNull(inMsg);
assertEquals("handle message was not invoked",2,handler1.getHandleMessageInvoked());
assertEquals("handle message was not invoked",2,handler2.getHandleMessageInvoked());
assertEquals("handle message was not invoked",2,soapHandler1.getHandleMessageInvoked());
assertEquals("handle message was not invoked",2,soapHandler2.getHandleMessageInvoked());
assertEquals("close must be called",1,handler1.getCloseInvoked());
assertEquals("close must be called",1,handler2.getCloseInvoked());
assertEquals("close must be called",1,soapHandler1.getCloseInvoked());
assertEquals("close must be called",1,soapHandler2.getCloseInvoked());
String[] handlerNames={"soapHandler4","soapHandler3","handler2","handler1","servant","handler1","handler2","soapHandler3","soapHandler4"};
List resp=getHandlerNames(inMsg.getSOAPPart().getEnvelope().getBody());
assertEquals(handlerNames.length,resp.size());
Iterator iter=resp.iterator();
for ( String expected : handlerNames) {
assertEquals(expected,iter.next());
}
}
APIUtilityVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testLogicalHandlerHandleMessageThrowsRuntimeExceptionClientInbound() throws Exception {
final String clientHandlerMessage="handler1 client side";
TestHandler handler1=new TestHandler(false);
TestHandler handler2=new TestHandler(false){
public boolean handleMessage( LogicalMessageContext ctx){
super.handleMessage(ctx);
Boolean outbound=(Boolean)ctx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (!outbound) {
throw new RuntimeException(clientHandlerMessage);
}
return true;
}
}
;
TestSOAPHandler soapHandler1=new TestSOAPHandler(false);
addHandlersToChain((BindingProvider)handlerTest,handler1,handler2,soapHandler1);
try {
handlerTest.ping();
fail("did not get expected exception");
}
catch ( RuntimeException e) {
assertTrue(e.getMessage().contains(clientHandlerMessage));
}
assertEquals(1,handler1.getHandleMessageInvoked());
assertEquals(2,handler2.getHandleMessageInvoked());
assertEquals(2,soapHandler1.getHandleMessageInvoked());
assertEquals(0,handler2.getHandleFaultInvoked());
assertEquals(0,handler1.getHandleFaultInvoked());
assertEquals(0,soapHandler1.getHandleFaultInvoked());
assertEquals(1,handler1.getCloseInvoked());
assertEquals(1,handler2.getCloseInvoked());
assertEquals(1,soapHandler1.getCloseInvoked());
assertTrue(handler2.getInvokeOrderOfClose() < handler1.getInvokeOrderOfClose());
}
InternalCallVerifier EqualityVerifier
@Test public void testSOAPHandlerHandleMessageReturnsFalseServerInbound() throws PingException {
String[] expectedHandlers={"soapHandler4","soapHandler3","soapHandler4"};
List resp=handlerTest.pingWithArgs("soapHandler3 inbound stop");
assertEquals(expectedHandlers.length,resp.size());
int i=0;
for ( String expected : expectedHandlers) {
assertEquals(expected,resp.get(i++));
}
}
APIUtilityVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testLogicalHandlerHandleMessageThrowsProtocolExceptionClientOutbound() throws Exception {
final String clientHandlerMessage="handler1 client side";
TestHandler handler1=new TestHandler(false);
TestHandler handler2=new TestHandler(false){
public boolean handleMessage( LogicalMessageContext ctx){
super.handleMessage(ctx);
Boolean outbound=(Boolean)ctx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outbound) {
throw new ProtocolException(clientHandlerMessage);
}
return true;
}
}
;
TestSOAPHandler soapHandler1=new TestSOAPHandler(false);
addHandlersToChain((BindingProvider)handlerTest,handler1,handler2,soapHandler1);
try {
handlerTest.ping();
fail("did not get expected exception");
}
catch ( ProtocolException e) {
assertEquals(clientHandlerMessage,e.getMessage());
}
assertEquals(1,handler1.getHandleMessageInvoked());
assertEquals(1,handler2.getHandleMessageInvoked());
assertEquals(0,soapHandler1.getHandleMessageInvoked());
assertEquals(0,handler2.getHandleFaultInvoked());
assertEquals(1,handler1.getHandleFaultInvoked());
assertEquals(0,soapHandler1.getHandleFaultInvoked());
assertEquals(1,handler1.getCloseInvoked());
assertEquals(1,handler2.getCloseInvoked());
assertEquals(0,soapHandler1.getCloseInvoked());
assertTrue(handler2.getInvokeOrderOfClose() < handler1.getInvokeOrderOfClose());
}
InternalCallVerifier EqualityVerifier PublicFieldVerifier
@Test public void testAddHandlerThroughHandlerResolverClientSide() throws Exception {
TestHandler handler1=new TestHandler(false);
TestHandler handler2=new TestHandler(false);
MyHandlerResolver myHandlerResolver=new MyHandlerResolver(handler1,handler2);
service.setHandlerResolver(myHandlerResolver);
HandlerTest handlerTestNew=service.getPort(portName,HandlerTest.class);
setAddress(handlerTestNew,"http://localhost:" + port + "/HandlerTest/SoapPort");
handlerTestNew.pingOneWay();
String bindingID=myHandlerResolver.bindingID;
assertEquals("http://schemas.xmlsoap.org/wsdl/soap/http",bindingID);
assertEquals(1,handler1.getHandleMessageInvoked());
assertEquals(1,handler2.getHandleMessageInvoked());
JAXBContext context=JAXBContext.newInstance(org.apache.handler_test.types.ObjectFactory.class);
Dispatch disp=service.createDispatch(portName,context,Service.Mode.PAYLOAD);
setAddress(disp,"http://localhost:" + port + "/HandlerTest/SoapPort");
disp.invokeOneWay(new org.apache.handler_test.types.PingOneWay());
assertEquals(2,handler1.getHandleMessageInvoked());
assertEquals(2,handler2.getHandleMessageInvoked());
}
APIUtilityVerifier BranchVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testServerEndpointRemoteFault() throws PingException {
TestHandler handler1=new TestHandler(false);
TestHandler handler2=new TestHandler(false){
public boolean handleFault( LogicalMessageContext ctx){
super.handleFault(ctx);
try {
Boolean outbound=(Boolean)ctx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (!outbound) {
LogicalMessage msg=ctx.getMessage();
String payload=convertDOMToString(msg.getPayload());
assertTrue(payload.indexOf("" + "servant throws SOAPFaultException" + " ") > -1);
}
}
catch ( Exception e) {
e.printStackTrace();
fail(e.toString());
}
return true;
}
private String convertDOMToString( Source s) throws TransformerException {
StringWriter stringWriter=new StringWriter();
StreamResult streamResult=new StreamResult(stringWriter);
TransformerFactory transformerFactory=TransformerFactory.newInstance();
Transformer transformer=transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT,"no");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","2");
transformer.setOutputProperty(OutputKeys.METHOD,"xml");
transformer.transform(s,streamResult);
return stringWriter.toString();
}
}
;
TestSOAPHandler soapHandler1=new TestSOAPHandler(false);
TestSOAPHandler soapHandler2=new TestSOAPHandler(false){
public boolean handleFault( SOAPMessageContext ctx){
super.handleFault(ctx);
try {
Boolean outbound=(Boolean)ctx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (!outbound) {
SOAPEnvelope env=ctx.getMessage().getSOAPPart().getEnvelope();
assertTrue("expected SOAPFault in SAAJ model",env.getBody().hasFault());
}
}
catch ( Exception e) {
e.printStackTrace();
fail(e.toString());
}
return true;
}
}
;
addHandlersToChain((BindingProvider)handlerTest,handler1,handler2,soapHandler1,soapHandler2);
try {
handlerTest.pingWithArgs("servant throw SOAPFaultException");
fail("did not get expected Exception");
}
catch ( SOAPFaultException sfe) {
}
assertEquals(1,handler1.getHandleMessageInvoked());
assertEquals(1,handler2.getHandleMessageInvoked());
assertEquals(1,soapHandler1.getHandleMessageInvoked());
assertEquals(1,soapHandler2.getHandleMessageInvoked());
assertEquals(1,handler2.getHandleFaultInvoked());
assertEquals(1,handler1.getHandleFaultInvoked());
assertEquals(1,soapHandler1.getHandleFaultInvoked());
assertEquals(1,soapHandler2.getHandleFaultInvoked());
assertEquals(1,handler1.getCloseInvoked());
assertEquals(1,handler2.getCloseInvoked());
assertEquals(1,soapHandler1.getCloseInvoked());
assertEquals(1,soapHandler2.getCloseInvoked());
assertTrue(handler2.getInvokeOrderOfClose() < handler1.getInvokeOrderOfClose());
}
APIUtilityVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testSOAPHandlerHandleMessageThrowsRuntimeExceptionClientOutbound() throws Exception {
final String clientHandlerMessage="handler1 client side";
TestHandler handler1=new TestHandler(false);
TestHandler handler2=new TestHandler(false);
TestSOAPHandler soapHandler1=new TestSOAPHandler(false){
public boolean handleMessage( SOAPMessageContext ctx){
super.handleMessage(ctx);
Boolean outbound=(Boolean)ctx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outbound) {
throw new RuntimeException(clientHandlerMessage);
}
return true;
}
}
;
TestSOAPHandler soapHandler2=new TestSOAPHandler(false);
addHandlersToChain((BindingProvider)handlerTest,handler1,handler2,soapHandler1,soapHandler2);
try {
handlerTest.ping();
fail("did not get expected exception");
}
catch ( RuntimeException e) {
assertTrue(e.getMessage().contains(clientHandlerMessage));
}
assertEquals(1,handler1.getHandleMessageInvoked());
assertEquals(1,handler2.getHandleMessageInvoked());
assertEquals(1,soapHandler1.getHandleMessageInvoked());
assertEquals(0,soapHandler2.getHandleMessageInvoked());
assertEquals(0,handler2.getHandleFaultInvoked());
assertEquals(0,handler1.getHandleFaultInvoked());
assertEquals(0,soapHandler1.getHandleFaultInvoked());
assertEquals(0,soapHandler2.getHandleFaultInvoked());
assertEquals(1,handler1.getCloseInvoked());
assertEquals(1,handler2.getCloseInvoked());
assertEquals(1,soapHandler1.getCloseInvoked());
assertEquals(0,soapHandler2.getCloseInvoked());
assertTrue(handler2.getInvokeOrderOfClose() < handler1.getInvokeOrderOfClose());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testAddingUnusedHandlersThroughConfigFile(){
HandlerTestServiceWithAnnotation service1=new HandlerTestServiceWithAnnotation(wsdl,serviceName);
HandlerTest handlerTest1=service1.getPort(portName,HandlerTest.class);
BindingProvider bp1=(BindingProvider)handlerTest1;
Binding binding1=bp1.getBinding();
@SuppressWarnings("rawtypes") List port1HandlerChain=binding1.getHandlerChain();
assertEquals(1,port1HandlerChain.size());
}
InternalCallVerifier EqualityVerifier
@Test public void testLogicalHandlerHandleMessageReturnsFalseServerInbound() throws PingException {
String[] expectedHandlers={"soapHandler4","soapHandler3","handler2","soapHandler3","soapHandler4"};
List resp=handlerTest.pingWithArgs("handler2 inbound stop");
assertEquals(expectedHandlers.length,resp.size());
int i=0;
for ( String expected : expectedHandlers) {
assertEquals(expected,resp.get(i++));
}
}
InternalCallVerifier EqualityVerifier
@Test public void testSOAPHandlerHandleMessageReturnsFalseServerOutbound() throws PingException {
String[] expectedHandlers={"soapHandler3 outbound stop","soapHandler4","soapHandler3","handler2","handler1","handler1","handler2","soapHandler3"};
List resp=handlerTest.pingWithArgs("soapHandler3 outbound stop");
assertEquals(expectedHandlers.length,resp.size());
int i=0;
for ( String expected : expectedHandlers) {
assertEquals(expected,resp.get(i++));
}
}
InternalCallVerifier NullVerifier
@Test public void testHandlerMessgeContext() throws PingException {
MessageContextFirstHandler handler1=new MessageContextFirstHandler();
MessageContextSecondHandler handler2=new MessageContextSecondHandler();
addHandlersToChain((BindingProvider)handlerTest,handler1,handler2);
List resp=handlerTest.ping();
assertNotNull(resp);
assertNotNull("handler2 can't retrieve header map from message context",handler2.getHeaderMap());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testLogicalHandlerHandleMessageReturnFalseClientInBound() throws Exception {
TestHandler handler1=new TestHandler(false);
TestHandler handler2=new TestHandler(false){
public boolean handleMessage( LogicalMessageContext ctx){
super.handleMessage(ctx);
Boolean outbound=(Boolean)ctx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (!outbound) {
return false;
}
return true;
}
}
;
TestHandler handler3=new TestHandler(false);
TestSOAPHandler soapHandler1=new TestSOAPHandler(false);
addHandlersToChain((BindingProvider)handlerTest,handler1,handler2,handler3,soapHandler1);
handlerTest.ping();
assertEquals(1,handler1.getHandleMessageInvoked());
assertEquals(2,handler2.getHandleMessageInvoked());
assertEquals(2,handler3.getHandleMessageInvoked());
assertEquals(2,soapHandler1.getHandleMessageInvoked());
assertEquals("close must be called",1,handler1.getCloseInvoked());
assertEquals("close must be called",1,handler2.getCloseInvoked());
assertEquals("close must be called",1,handler3.getCloseInvoked());
assertEquals("close must be called",1,soapHandler1.getCloseInvoked());
assertTrue(soapHandler1.getInvokeOrderOfClose() < handler3.getInvokeOrderOfClose());
assertTrue(handler3.getInvokeOrderOfClose() < handler2.getInvokeOrderOfClose());
assertTrue(handler2.getInvokeOrderOfClose() < handler1.getInvokeOrderOfClose());
}
APIUtilityVerifier UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSOAPHandlerHandleMessageThrowsSOAPFaultExceptionServerInbound() throws PingException {
try {
handlerTest.pingWithArgs("soapHandler3 inbound throw SOAPFaultExceptionWDetail");
fail("did not get expected SOAPFaultException");
}
catch ( SOAPFaultException e) {
assertEquals("HandleMessage throws exception",e.getMessage());
SOAPFault fault=e.getFault();
assertNotNull(fault);
assertEquals(new QName(SOAPConstants.URI_NS_SOAP_ENVELOPE,"Server"),fault.getFaultCodeAsQName());
assertEquals("http://gizmos.com/orders",fault.getFaultActor());
Detail detail=fault.getDetail();
assertNotNull(detail);
QName nn=new QName("http://gizmos.com/orders/","order");
Element el=DOMUtils.getFirstChildWithName(detail,nn);
assertNotNull(el);
el.normalize();
assertEquals("Quantity element does not have a value",el.getFirstChild().getNodeValue());
el=DOMUtils.getNextElement(el);
el.normalize();
assertEquals("Incomplete address: no zip code",el.getFirstChild().getNodeValue());
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testLogicalHandlerHandleMessageThrowsProtocolExceptionClientInbound() throws Exception {
final String clientHandlerMessage="handler1 client side";
TestHandler handler1=new TestHandler(false);
TestHandler handler2=new TestHandler(false){
public boolean handleMessage( LogicalMessageContext ctx){
super.handleMessage(ctx);
Boolean outbound=(Boolean)ctx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (!outbound) {
throw new ProtocolException(clientHandlerMessage);
}
return true;
}
}
;
TestSOAPHandler soapHandler1=new TestSOAPHandler(false);
addHandlersToChain((BindingProvider)handlerTest,handler1,handler2,soapHandler1);
try {
handlerTest.ping();
}
catch ( ProtocolException e) {
assertEquals(clientHandlerMessage,e.getMessage());
}
assertEquals(1,handler1.getHandleMessageInvoked());
assertEquals(2,handler2.getHandleMessageInvoked());
assertEquals(2,soapHandler1.getHandleMessageInvoked());
assertEquals(0,handler2.getHandleFaultInvoked());
assertEquals(0,handler1.getHandleFaultInvoked());
assertEquals(0,soapHandler1.getHandleFaultInvoked());
assertEquals(1,handler1.getCloseInvoked());
assertEquals(1,handler2.getCloseInvoked());
assertEquals(1,soapHandler1.getCloseInvoked());
assertTrue(handler2.getInvokeOrderOfClose() < handler1.getInvokeOrderOfClose());
}
APIUtilityVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testLogicalHandlerHandleMessageThrowsRuntimeExceptionClientOutbound() throws Exception {
final String clientHandlerMessage="handler1 client side";
TestHandler handler1=new TestHandler(false);
TestHandler handler2=new TestHandler(false){
public boolean handleMessage( LogicalMessageContext ctx){
super.handleMessage(ctx);
Boolean outbound=(Boolean)ctx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outbound) {
throw new RuntimeException(clientHandlerMessage);
}
return true;
}
}
;
TestSOAPHandler soapHandler1=new TestSOAPHandler(false);
addHandlersToChain((BindingProvider)handlerTest,handler1,handler2,soapHandler1);
try {
handlerTest.ping();
fail("did not get expected exception");
}
catch ( RuntimeException e) {
assertTrue(e.getMessage().contains(clientHandlerMessage));
}
assertEquals(1,handler1.getHandleMessageInvoked());
assertEquals(1,handler2.getHandleMessageInvoked());
assertEquals(0,soapHandler1.getHandleMessageInvoked());
assertEquals(0,handler2.getHandleFaultInvoked());
assertEquals(0,handler1.getHandleFaultInvoked());
assertEquals(0,soapHandler1.getHandleFaultInvoked());
assertEquals(1,handler1.getCloseInvoked());
assertEquals(1,handler2.getCloseInvoked());
assertEquals(0,soapHandler1.getCloseInvoked());
assertTrue(handler2.getInvokeOrderOfClose() < handler1.getInvokeOrderOfClose());
}
APIUtilityVerifier BranchVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testLogicalHandlerHandleMessageReturnFalseClientOutBound() throws Exception {
final String clientHandlerMessage="handler2 client side";
TestHandler handler1=new TestHandler(false);
TestHandler handler2=new TestHandler(false){
public boolean handleMessage( LogicalMessageContext ctx){
super.handleMessage(ctx);
try {
Boolean outbound=(Boolean)ctx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outbound) {
LogicalMessage msg=ctx.getMessage();
assertNotNull("logical message is null",msg);
JAXBContext jaxbCtx=JAXBContext.newInstance(PackageUtils.getPackageName(PingOneWay.class));
PingResponse resp=new PingResponse();
resp.getHandlersInfo().add(clientHandlerMessage);
msg.setPayload(resp,jaxbCtx);
return false;
}
}
catch ( Exception e) {
e.printStackTrace();
fail(e.toString());
}
return true;
}
}
;
TestHandler handler3=new TestHandler(false);
TestSOAPHandler soapHandler1=new TestSOAPHandler(false);
addHandlersToChain((BindingProvider)handlerTest,handler1,handler2,handler3,soapHandler1);
List resp=handlerTest.ping();
assertEquals(clientHandlerMessage,resp.get(0));
assertEquals("the first handler must be invoked twice",2,handler1.getHandleMessageInvoked());
assertEquals("the second handler must be invoked once only on outbound",1,handler2.getHandleMessageInvoked());
assertEquals("the third handler must not be invoked",0,handler3.getHandleMessageInvoked());
assertEquals("the last handler must not be invoked",0,soapHandler1.getHandleMessageInvoked());
assertEquals("close must be called",1,handler1.getCloseInvoked());
assertEquals("close must be called",1,handler2.getCloseInvoked());
assertEquals("close must be called",0,handler3.getCloseInvoked());
assertEquals("close must be called",0,soapHandler1.getCloseInvoked());
assertTrue(handler2.getInvokeOrderOfClose() < handler1.getInvokeOrderOfClose());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testSOAPHandlerHandleMessageThrowsProtocolExceptionClientInbound() throws Exception {
final String clientHandlerMessage="handler1 client side";
TestHandler handler1=new TestHandler(false);
TestHandler handler2=new TestHandler(false);
TestSOAPHandler soapHandler1=new TestSOAPHandler(false){
public boolean handleMessage( SOAPMessageContext ctx){
super.handleMessage(ctx);
Boolean outbound=(Boolean)ctx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (!outbound) {
throw new ProtocolException(clientHandlerMessage);
}
return true;
}
}
;
TestSOAPHandler soapHandler2=new TestSOAPHandler(false);
addHandlersToChain((BindingProvider)handlerTest,handler1,handler2,soapHandler1,soapHandler2);
try {
handlerTest.ping();
}
catch ( ProtocolException e) {
assertEquals(clientHandlerMessage,e.getMessage());
}
assertEquals(1,handler1.getHandleMessageInvoked());
assertEquals(1,handler2.getHandleMessageInvoked());
assertEquals(2,soapHandler1.getHandleMessageInvoked());
assertEquals(2,soapHandler2.getHandleMessageInvoked());
assertEquals(0,handler2.getHandleFaultInvoked());
assertEquals(0,handler1.getHandleFaultInvoked());
assertEquals(0,soapHandler1.getHandleFaultInvoked());
assertEquals(0,soapHandler2.getHandleFaultInvoked());
assertEquals(1,handler1.getCloseInvoked());
assertEquals(1,handler2.getCloseInvoked());
assertEquals(1,soapHandler1.getCloseInvoked());
assertEquals(1,soapHandler2.getCloseInvoked());
assertTrue(handler2.getInvokeOrderOfClose() < handler1.getInvokeOrderOfClose());
}
APIUtilityVerifier BranchVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSOAPHandlerHandleMessageReturnFalseClientOutbound() throws Exception {
final String clientHandlerMessage="client side";
TestHandler handler1=new TestHandler(false);
TestHandler handler2=new TestHandler(false){
public boolean handleMessage( LogicalMessageContext ctx){
super.handleMessage(ctx);
try {
Boolean outbound=(Boolean)ctx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outbound) {
LogicalMessage msg=ctx.getMessage();
assertNotNull("logical message is null",msg);
JAXBContext jaxbCtx=JAXBContext.newInstance(PackageUtils.getPackageName(PingOneWay.class));
PingResponse resp=new PingResponse();
resp.getHandlersInfo().add(clientHandlerMessage);
msg.setPayload(resp,jaxbCtx);
}
}
catch ( Exception e) {
e.printStackTrace();
fail(e.toString());
}
return true;
}
}
;
TestSOAPHandler soapHandler1=new TestSOAPHandler(false);
TestSOAPHandler soapHandler2=new TestSOAPHandler(false){
public boolean handleMessage( SOAPMessageContext ctx){
super.handleMessage(ctx);
Boolean outbound=(Boolean)ctx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outbound) {
return false;
}
return true;
}
}
;
addHandlersToChain((BindingProvider)handlerTest,handler1,handler2,soapHandler1,soapHandler2);
List resp=handlerTest.ping();
assertEquals(clientHandlerMessage,resp.get(0));
assertEquals(2,handler1.getHandleMessageInvoked());
assertEquals(2,handler2.getHandleMessageInvoked());
assertEquals(2,soapHandler1.getHandleMessageInvoked());
assertEquals(1,soapHandler2.getHandleMessageInvoked());
assertEquals("close must be called",1,handler1.getCloseInvoked());
assertEquals("close must be called",1,handler2.getCloseInvoked());
assertEquals("close must be called",1,soapHandler1.getCloseInvoked());
assertEquals("close must be called",1,soapHandler2.getCloseInvoked());
assertTrue(soapHandler2.getInvokeOrderOfClose() < soapHandler1.getInvokeOrderOfClose());
assertTrue(soapHandler1.getInvokeOrderOfClose() < handler2.getInvokeOrderOfClose());
assertTrue(handler2.getInvokeOrderOfClose() < handler1.getInvokeOrderOfClose());
}
Class: org.apache.cxf.systest.handlers.HandlerInvocationUsingAddNumbersTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testHandlerInjectingResource() throws Exception {
Bus bus=BusFactory.getDefaultBus();
ResourceManager resourceManager=bus.getExtension(ResourceManager.class);
assertNotNull(resourceManager);
resourceManager.addResourceResolver(new TestResourceResolver());
URL wsdl=getClass().getResource("/wsdl/addNumbers.wsdl");
AddNumbersServiceWithAnnotation service=new AddNumbersServiceWithAnnotation(wsdl,serviceName);
AddNumbers port=service.getPort(portName,AddNumbers.class);
setAddress(port,addNumbersAddress);
@SuppressWarnings("rawtypes") List handlerChain=((BindingProvider)port).getBinding().getHandlerChain();
SmallNumberHandler h=(SmallNumberHandler)handlerChain.get(0);
assertEquals("injectedValue",h.getInjectedString());
}
InternalCallVerifier EqualityVerifier
@Test public void testAddHandlerProgrammaticallyClientSide() throws Exception {
URL wsdl=getClass().getResource("/wsdl/addNumbers.wsdl");
AddNumbersService service=new AddNumbersService(wsdl,serviceName);
AddNumbers port=service.getPort(portName,AddNumbers.class);
setAddress(port,addNumbersAddress);
SmallNumberHandler sh=new SmallNumberHandler();
addHandlersProgrammatically((BindingProvider)port,sh);
int result=port.addNumbers(10,20);
assertEquals(200,result);
int result1=port.addNumbers(5,6);
assertEquals(11,result1);
}
APIUtilityVerifier BranchVerifier UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testInvokeFromDispatchWithJAXBPayload() throws Exception {
URL wsdl=getClass().getResource("/wsdl/addNumbers.wsdl");
assertNotNull(wsdl);
AddNumbersService service=new AddNumbersService(wsdl,serviceName);
assertNotNull(service);
JAXBContext jc=JAXBContext.newInstance("org.apache.handlers.types");
Dispatch disp=service.createDispatch(portName,jc,Service.Mode.PAYLOAD);
setAddress(disp,addNumbersAddress);
SmallNumberHandler sh=new SmallNumberHandler();
TestSOAPHandler soapHandler=new TestSOAPHandler(false){
public boolean handleMessage( SOAPMessageContext ctx){
super.handleMessage(ctx);
Boolean outbound=(Boolean)ctx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outbound) {
try {
SOAPMessage msg=ctx.getMessage();
assertNotNull(msg);
}
catch ( Exception e) {
e.printStackTrace();
fail(e.toString());
}
}
return true;
}
}
;
addHandlersProgrammatically(disp,sh,soapHandler);
org.apache.handlers.types.AddNumbers req=new org.apache.handlers.types.AddNumbers();
req.setArg0(10);
req.setArg1(20);
ObjectFactory factory=new ObjectFactory();
JAXBElement e=factory.createAddNumbers(req);
JAXBElement> response=(JAXBElement>)disp.invoke(e);
assertNotNull(response);
AddNumbersResponse value=(AddNumbersResponse)response.getValue();
assertEquals(200,value.getReturn());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testHandlerPostConstruct() throws Exception {
URL wsdl=getClass().getResource("/wsdl/addNumbers.wsdl");
AddNumbersServiceWithAnnotation service=new AddNumbersServiceWithAnnotation(wsdl,serviceName);
AddNumbers port=service.getPort(portName,AddNumbers.class);
setAddress(port,addNumbersAddress);
@SuppressWarnings("rawtypes") List handlerChain=((BindingProvider)port).getBinding().getHandlerChain();
SmallNumberHandler h=(SmallNumberHandler)handlerChain.get(0);
assertTrue(h.isPostConstructInvoked());
}
InternalCallVerifier EqualityVerifier
@Test public void testAddHandlerByAnnotationClientSide() throws Exception {
URL wsdl=getClass().getResource("/wsdl/addNumbers.wsdl");
AddNumbersServiceWithAnnotation service=new AddNumbersServiceWithAnnotation(wsdl,serviceName);
AddNumbers port=service.getPort(portName,AddNumbers.class);
setAddress(port,addNumbersAddress);
int result=port.addNumbers(10,20);
assertEquals(200,result);
int result1=port.addNumbers(5,6);
assertEquals(11,result1);
}
Class: org.apache.cxf.systest.handlers.SpringConfiguredAutoRewriteSoapAddressTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testWsdlAddress() throws Exception {
AddNumbers addNumbers=getApplicationContext().getBean("cxfHandlerTestClientEndpoint",AddNumbers.class);
int r=addNumbers.addNumbers(10,15);
assertEquals(1015,r);
List serviceUrls=findAllServiceUrlsFromWsdl("localhost",port);
assertEquals(1,serviceUrls.size());
assertEquals("http://localhost:" + port + "/SpringEndpoint",serviceUrls.get(0));
String version=System.getProperty("java.version");
if (version.startsWith("1.8")) {
return;
}
serviceUrls=findAllServiceUrlsFromWsdl("127.0.0.1",port);
assertEquals(1,serviceUrls.size());
assertEquals("http://127.0.0.1:" + port + "/SpringEndpoint",serviceUrls.get(0));
}
Class: org.apache.cxf.systest.handlers.SpringConfiguredHandlerTest InternalCallVerifier EqualityVerifier
@Test public void testSpringConfiguresHandlers() throws Exception {
AddNumbers addNumbers=getApplicationContext().getBean("cxfHandlerTestClientEndpoint",AddNumbers.class);
int r=addNumbers.addNumbers(10,15);
assertEquals(1015,r);
addNumbers=getApplicationContext().getBean("cxfHandlerTestClientEndpointNoHandler",AddNumbers.class);
r=addNumbers.addNumbers(10,15);
assertEquals(115,r);
addNumbers=getApplicationContext().getBean("cxfHandlerTestClientServer",AddNumbers.class);
r=addNumbers.addNumbers(10,15);
assertEquals(1015,r);
}
Class: org.apache.cxf.systest.handlers.SpringConfiguredNoAutoRewriteSoapAddressTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testWsdlAddress() throws Exception {
AddNumbers addNumbers=getApplicationContext().getBean("cxfHandlerTestClientEndpoint",AddNumbers.class);
int r=addNumbers.addNumbers(10,15);
assertEquals(1015,r);
List serviceUrls=findAllServiceUrlsFromWsdl("localhost",port);
assertEquals(1,serviceUrls.size());
assertEquals("http://localhost:" + port + "/SpringEndpoint",serviceUrls.get(0));
String version=System.getProperty("java.version");
if (version.startsWith("1.8")) {
return;
}
serviceUrls=findAllServiceUrlsFromWsdl("127.0.0.1",port);
assertEquals(1,serviceUrls.size());
assertEquals("http://localhost:" + port + "/SpringEndpoint",serviceUrls.get(0));
}
Class: org.apache.cxf.systest.handlers.TrivialSOAPHandlerTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testInvocation() throws Exception {
GreeterService service=new GreeterService();
assertNotNull(service);
try {
Greeter greeter=service.getGreeterPort();
setAddress(greeter,address);
String greeting=greeter.greetMe("Bonjour");
assertNotNull("no response received from service",greeting);
assertEquals("BONJOUR",greeting);
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
Class: org.apache.cxf.systest.http.ClientServerSessionTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testInvocationWithPerRequestAnnotation() throws Exception {
GreeterService service=new GreeterService();
assertNotNull(service);
Greeter greeter=service.getGreeterPort();
BindingProvider bp=(BindingProvider)greeter;
bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"http://localhost:" + PORT + "/PerRequest");
bp.getRequestContext().put(BindingProvider.SESSION_MAINTAIN_PROPERTY,true);
String result=greeter.greetMe("World");
assertEquals("Hello World",result);
assertEquals("Bonjour default",greeter.sayHi());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testInvocationWithSpringBeanAnnotation() throws Exception {
GreeterService service=new GreeterService();
assertNotNull(service);
Greeter greeter=service.getGreeterPort();
BindingProvider bp=(BindingProvider)greeter;
bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"http://localhost:" + PORT + "/SpringBean");
bp.getRequestContext().put(BindingProvider.SESSION_MAINTAIN_PROPERTY,true);
String result=greeter.greetMe("World");
assertEquals("Hello World",result);
assertEquals("Bonjour World",greeter.sayHi());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testInvocationWithSession() throws Exception {
GreeterService service=new GreeterService();
assertNotNull(service);
try {
Greeter greeter=service.getGreeterPort();
BindingProvider bp=(BindingProvider)greeter;
updateAddressPort(bp,PORT);
bp.getRequestContext().put(BindingProvider.SESSION_MAINTAIN_PROPERTY,true);
Map> headers=CastUtils.cast((Map,?>)bp.getRequestContext().get("javax.xml.ws.http.request.headers"));
if (headers == null) {
headers=new HashMap>();
bp.getRequestContext().put("javax.xml.ws.http.request.headers",headers);
}
List cookies=Arrays.asList(new String[]{"a=a","b=b"});
headers.put("Cookie",cookies);
String greeting=greeter.greetMe("Bonjour");
String cookie="";
if (greeting.indexOf(';') != -1) {
cookie=greeting.substring(greeting.indexOf(';'));
greeting=greeting.substring(0,greeting.indexOf(';'));
}
assertNotNull("no response received from service",greeting);
assertEquals("Hello Bonjour",greeting);
assertTrue(cookie.contains("a=a"));
assertTrue(cookie.contains("b=b"));
greeting=greeter.greetMe("Hello");
cookie="";
if (greeting.indexOf(';') != -1) {
cookie=greeting.substring(greeting.indexOf(';'));
greeting=greeting.substring(0,greeting.indexOf(';'));
}
assertNotNull("no response received from service",greeting);
assertEquals("Hello Bonjour",greeting);
assertTrue(cookie.contains("a=a"));
assertTrue(cookie.contains("b=b"));
greeting=greeter.greetMe("NiHao");
cookie="";
if (greeting.indexOf(';') != -1) {
cookie=greeting.substring(greeting.indexOf(';'));
greeting=greeting.substring(0,greeting.indexOf(';'));
}
assertNotNull("no response received from service",greeting);
assertEquals("Hello Hello",greeting);
assertTrue(cookie.contains("a=a"));
assertTrue(cookie.contains("b=b"));
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testInvocationWithoutSession() throws Exception {
GreeterService service=new GreeterService();
assertNotNull(service);
try {
Greeter greeter=service.getGreeterPort();
updateAddressPort(greeter,PORT);
String greeting=greeter.greetMe("Bonjour");
assertNotNull("no response received from service",greeting);
assertEquals("Hello Bonjour",greeting);
greeting=greeter.greetMe("Hello");
assertNotNull("no response received from service",greeting);
assertEquals("Hello Hello",greeting);
greeting=greeter.greetMe("NiHao");
assertNotNull("no response received from service",greeting);
assertEquals("Hello NiHao",greeting);
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testOnewayInvocationWithSession() throws Exception {
GreeterService service=new GreeterService();
assertNotNull(service);
try {
Greeter greeter=service.getGreeterPort();
BindingProvider bp=(BindingProvider)greeter;
updateAddressPort(bp,PORT);
bp.getRequestContext().put(BindingProvider.SESSION_MAINTAIN_PROPERTY,true);
greeter.greetMeOneWay("Bonjour");
String greeting=greeter.greetMe("Hello");
if (greeting.indexOf(';') != -1) {
greeting=greeting.substring(0,greeting.indexOf(';'));
}
assertNotNull("no response received from service",greeting);
assertEquals("Hello Bonjour",greeting);
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
Class: org.apache.cxf.systest.http.HTTPConduitTest BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
/**
* This method tests if http to http redirects work.
* Rethwel redirects to Mortimer.
*/
@Test public void testHttp2HttpRedirect() throws Exception {
startServer("Mortimer");
startServer("Rethwel");
URL config=getClass().getResource("Http2HttpRedirect.cxf");
new DefaultBusFactory().createBus(config);
URL wsdl=getClass().getResource("greeting.wsdl");
assertNotNull("WSDL is null",wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
assertNotNull("Service is null",service);
Greeter rethwel=service.getPort(rethwelQ,Greeter.class);
updateAddressPort(rethwel,getPort("PORT1"));
assertNotNull("Port is null",rethwel);
configureProxy(ClientProxy.getClient(rethwel));
String answer=rethwel.sayHi();
assertTrue("Unexpected answer: " + answer,"Bonjour from Mortimer".equals(answer));
assertProxyRequestCount(2);
}
BooleanVerifier InternalCallVerifier
@Test public void testBasicConnection() throws Exception {
startServer("Mortimer");
Greeter mortimer=getMortimerGreeter();
String answer=mortimer.sayHi();
answer=mortimer.sayHi();
answer=mortimer.sayHi();
assertTrue("Unexpected answer: " + answer,"Bonjour from Mortimer".equals(answer));
assertProxyRequestCount(3);
}
UtilityVerifier InternalCallVerifier NullVerifier HybridVerifier
/**
* This methods tests that a redirection loop will fail.
* Hurlon redirects to Abost, which redirects to Hurlon.
* Note: Unfortunately, the invocation may "fail" for any
* number of reasons.
*/
@Test public void testHttp2HttpLoopRedirectFail() throws Exception {
startServer("Abost");
startServer("Hurlon");
URL config=getClass().getResource("Http2HttpLoopRedirectFail.cxf");
new DefaultBusFactory().createBus(config);
URL wsdl=getClass().getResource("greeting.wsdl");
assertNotNull("WSDL is null",wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
assertNotNull("Service is null",service);
Greeter hurlon=service.getPort(hurlonQ,Greeter.class);
assertNotNull("Port is null",hurlon);
updateAddressPort(hurlon,getPort("PORT3"));
configureProxy(ClientProxy.getClient(hurlon));
String answer=null;
try {
answer=hurlon.sayHi();
fail("Redirect didn't fail. Got answer: " + answer);
}
catch ( Exception e) {
}
assertProxyRequestCount(2);
}
UtilityVerifier InternalCallVerifier NullVerifier HybridVerifier
/**
* This methods tests that a conduit that is not configured
* to follow redirects will not. The default is not to
* follow redirects.
* Rethwel redirects to Mortimer.
* Note: Unfortunately, the invocation will
* "fail" for any number of other reasons.
*/
@Test public void testHttp2HttpRedirectFail() throws Exception {
startServer("Mortimer");
startServer("Rethwel");
URL wsdl=getClass().getResource("greeting.wsdl");
assertNotNull("WSDL is null",wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
assertNotNull("Service is null",service);
Greeter rethwel=service.getPort(rethwelQ,Greeter.class);
assertNotNull("Port is null",rethwel);
updateAddressPort(rethwel,getPort("PORT1"));
configureProxy(ClientProxy.getClient(rethwel));
String answer=null;
try {
answer=rethwel.sayHi();
fail("Redirect didn't fail. Got answer: " + answer);
}
catch ( Exception e) {
}
assertProxyRequestCount(1);
}
Class: org.apache.cxf.systest.http.PublishedEndpointUrlTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testPublishedEndpointUrl() throws Exception {
Greeter implementor=new org.apache.hello_world_soap_http.GreeterImpl();
String publishedEndpointUrl="http://cxf.apache.org/publishedEndpointUrl";
Bus bus=BusFactory.getDefaultBus();
JaxWsServerFactoryBean svrFactory=new JaxWsServerFactoryBean();
svrFactory.setBus(bus);
svrFactory.setServiceClass(Greeter.class);
svrFactory.setAddress("http://localhost:" + PORT + "/publishedEndpointUrl");
svrFactory.setPublishedEndpointUrl(publishedEndpointUrl);
svrFactory.setServiceBean(implementor);
Server server=svrFactory.create();
WSDLReader wsdlReader=WSDLFactory.newInstance().newWSDLReader();
wsdlReader.setFeature("javax.wsdl.verbose",false);
URL url=new URL(svrFactory.getAddress() + "?wsdl=1");
HttpURLConnection connect=(HttpURLConnection)url.openConnection();
assertEquals(500,connect.getResponseCode());
Definition wsdl=wsdlReader.readWSDL(svrFactory.getAddress() + "?wsdl");
assertNotNull(wsdl);
Collection services=CastUtils.cast(wsdl.getAllServices().values());
final String failMesg="WSDL provided incorrect soap:address location";
for ( Service service : services) {
Collection ports=CastUtils.cast(service.getPorts().values());
for ( Port port : ports) {
List> extensions=port.getExtensibilityElements();
for ( Object extension : extensions) {
String actualUrl=null;
if (extension instanceof SOAP12Address) {
actualUrl=((SOAP12Address)extension).getLocationURI();
}
else if (extension instanceof SOAPAddress) {
actualUrl=((SOAPAddress)extension).getLocationURI();
}
assertEquals(failMesg,publishedEndpointUrl,actualUrl);
}
}
}
server.stop();
server.destroy();
bus.shutdown(true);
}
Class: org.apache.cxf.systest.http.auth.DigestAuthTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testDigestAuth() throws Exception {
URL wsdl=getClass().getResource("../greeting.wsdl");
assertNotNull("WSDL is null",wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
assertNotNull("Service is null",service);
Greeter mortimer=service.getPort(mortimerQ,Greeter.class);
assertNotNull("Port is null",mortimer);
TestUtil.setAddress(mortimer,"http://localhost:" + PORT + "/digestauth/greeter");
Client client=ClientProxy.getClient(mortimer);
HTTPConduit http=(HTTPConduit)client.getConduit();
AuthorizationPolicy authPolicy=new AuthorizationPolicy();
authPolicy.setAuthorizationType("Digest");
authPolicy.setUserName("foo");
authPolicy.setPassword("bar");
http.setAuthorization(authPolicy);
String answer=mortimer.sayHi();
assertEquals("Unexpected answer: " + answer,"Hi",answer);
}
APIUtilityVerifier UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testNoAuth() throws Exception {
URL wsdl=getClass().getResource("../greeting.wsdl");
assertNotNull("WSDL is null",wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
assertNotNull("Service is null",service);
Greeter mortimer=service.getPort(mortimerQ,Greeter.class);
assertNotNull("Port is null",mortimer);
TestUtil.setAddress(mortimer,"http://localhost:" + PORT + "/digestauth/greeter");
try {
String answer=mortimer.sayHi();
Assert.fail("Unexpected reply (" + answer + "). Should throw exception");
}
catch ( Exception e) {
Throwable cause=e.getCause();
Assert.assertEquals(HTTPException.class,cause.getClass());
HTTPException he=(HTTPException)cause;
Assert.assertEquals(401,he.getResponseCode());
}
}
Class: org.apache.cxf.systest.https.conduit.HTTPSConduitTest InternalCallVerifier NullVerifier
/**
* This methods tests a basic https connection to Bethal.
* It supplies an authorization policy with preemptive user/pass
* to avoid the 401.
*/
@Test public void testHttpsBasicConnectionWithConfig() throws Exception {
startServer("Bethal");
URL config=getClass().getResource("BethalClientConfig.cxf");
new DefaultBusFactory().createBus(config);
URL wsdl=getClass().getResource("greeting.wsdl");
assertNotNull("WSDL is null",wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
assertNotNull("Service is null",service);
Greeter bethal=service.getPort(bethalQ,Greeter.class);
assertNotNull("Port is null",bethal);
updateAddressPort(bethal,getPort("PORT4"));
verifyBethalClient(bethal);
}
UtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testHttpsTrustRedirect() throws Exception {
startServer("Tarpin");
startServer("Gordy");
startServer("Bethal");
URL wsdl=getClass().getResource("greeting.wsdl");
assertNotNull("WSDL is null",wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
assertNotNull("Service is null",service);
Greeter tarpin=service.getPort(tarpinQ,Greeter.class);
assertNotNull("Port is null",tarpin);
updateAddressPort(tarpin,getPort("PORT1"));
Client client=ClientProxy.getClient(tarpin);
HTTPConduit http=(HTTPConduit)client.getConduit();
HTTPClientPolicy httpClientPolicy=new HTTPClientPolicy();
httpClientPolicy.setAutoRedirect(true);
AuthorizationPolicy authPolicy=new AuthorizationPolicy();
authPolicy.setUserName("Betty");
authPolicy.setPassword("password");
http.setClient(httpClientPolicy);
http.setTlsClientParameters(tlsClientParameters);
http.setAuthorization(authPolicy);
MyHttpsTrustDecider trustDecider=new MyHttpsTrustDecider(new String[]{"Tarpin","Gordy","Bethal"});
http.setTrustDecider(trustDecider);
configureProxy(ClientProxy.getClient(tarpin));
String answer=tarpin.sayHi();
assertProxyRequestCount(0);
assertTrue("Trust Decider wasn't called correctly",3 == trustDecider.wasCalled());
assertTrue("Unexpected answer: " + answer,"Bonjour from Bethal".equals(answer));
http.getClient().setMaxRetransmits(1);
try {
answer=tarpin.sayHi();
fail("Unexpected answer from Tarpin: " + answer);
}
catch ( Exception e) {
}
assertProxyRequestCount(0);
http.getClient().setMaxRetransmits(-1);
trustDecider=new MyHttpsTrustDecider(new String[]{"Tarpin","Bethal"});
http.setTrustDecider(trustDecider);
try {
answer=tarpin.sayHi();
fail("Unexpected answer from Tarpin: " + answer);
}
catch ( Exception e) {
assertTrue("Trust Decider wasn't called correctly",2 == trustDecider.wasCalled());
}
assertProxyRequestCount(0);
}
UtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
/**
* This tests redirects through Gordy to Bethal. Bethal will
* supply a series of 401s. See PushBack401.
*/
@Test public void testHttpsRedirect401Response() throws Exception {
startServer("Gordy");
startServer("Bethal");
URL wsdl=getClass().getResource("greeting.wsdl");
assertNotNull("WSDL is null",wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
assertNotNull("Service is null",service);
Greeter gordy=service.getPort(gordyQ,Greeter.class);
assertNotNull("Port is null",gordy);
updateAddressPort(gordy,getPort("PORT3"));
Client client=ClientProxy.getClient(gordy);
HTTPConduit http=(HTTPConduit)client.getConduit();
HTTPClientPolicy httpClientPolicy=new HTTPClientPolicy();
httpClientPolicy.setAutoRedirect(true);
http.setClient(httpClientPolicy);
http.setTlsClientParameters(tlsClientParameters);
http.setTrustDecider(new MyHttpsTrustDecider(new String[]{"Gordy","Bethal"}));
http.setAuthSupplier(new MyBasicAuthSupplier("Cronus","Betty","password"));
String answer=gordy.sayHi();
assertTrue("Unexpected answer: " + answer,"Bonjour from Bethal".equals(answer));
http.setAuthSupplier(new MyBasicAuthSupplier());
try {
answer=gordy.sayHi();
fail("Unexpected answer from Gordy: " + answer);
}
catch ( Exception e) {
}
}
UtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testHttpsTrust() throws Exception {
startServer("Bethal");
URL wsdl=getClass().getResource("greeting.wsdl");
assertNotNull("WSDL is null",wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
assertNotNull("Service is null",service);
Greeter bethal=service.getPort(bethalQ,Greeter.class);
assertNotNull("Port is null",bethal);
updateAddressPort(bethal,getPort("PORT4"));
Client client=ClientProxy.getClient(bethal);
HTTPConduit http=(HTTPConduit)client.getConduit();
HTTPClientPolicy httpClientPolicy=new HTTPClientPolicy();
httpClientPolicy.setAutoRedirect(false);
AuthorizationPolicy authPolicy=new AuthorizationPolicy();
authPolicy.setUserName("Betty");
authPolicy.setPassword("password");
http.setClient(httpClientPolicy);
http.setTlsClientParameters(tlsClientParameters);
http.setAuthorization(authPolicy);
http.setTrustDecider(new MyHttpsTrustDecider("Bethal"));
configureProxy(client);
String answer=bethal.sayHi();
assertTrue("Unexpected answer: " + answer,"Bonjour from Bethal".equals(answer));
assertProxyRequestCount(0);
MyHttpsTrustDecider trustDecider=new MyHttpsTrustDecider("Nobody");
http.setTrustDecider(trustDecider);
try {
answer=bethal.sayHi();
fail("Unexpected answer from Bethal: " + answer);
}
catch ( Exception e) {
}
assertProxyRequestCount(0);
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
/**
* This methods tests a basic https connection to Bethal.
* It supplies an authorization policy with premetive user/pass
* to avoid the 401.
*/
@Test public void testHttpsBasicConnection() throws Exception {
startServer("Bethal");
URL wsdl=getClass().getResource("greeting.wsdl");
assertNotNull("WSDL is null",wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
assertNotNull("Service is null",service);
Greeter bethal=service.getPort(bethalQ,Greeter.class);
assertNotNull("Port is null",bethal);
updateAddressPort(bethal,getPort("PORT4"));
Client client=ClientProxy.getClient(bethal);
HTTPConduit http=(HTTPConduit)client.getConduit();
HTTPClientPolicy httpClientPolicy=new HTTPClientPolicy();
httpClientPolicy.setAutoRedirect(false);
AuthorizationPolicy authPolicy=new AuthorizationPolicy();
authPolicy.setUserName("Betty");
authPolicy.setPassword("password");
http.setClient(httpClientPolicy);
http.setTlsClientParameters(tlsClientParameters);
http.setAuthorization(authPolicy);
configureProxy(client);
String answer=bethal.sayHi();
assertTrue("Unexpected answer: " + answer,"Bonjour from Bethal".equals(answer));
assertProxyRequestCount(0);
}
InternalCallVerifier NullVerifier
@Test public void testHttpsRedirectToHttpFail() throws Exception {
startServer("Mortimer");
startServer("Poltim");
URL wsdl=getClass().getResource("greeting.wsdl");
assertNotNull("WSDL is null",wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
assertNotNull("Service is null",service);
Greeter poltim=service.getPort(poltimQ,Greeter.class);
assertNotNull("Port is null",poltim);
updateAddressPort(poltim,getPort("PORT2"));
Client client=ClientProxy.getClient(poltim);
HTTPConduit http=(HTTPConduit)client.getConduit();
HTTPClientPolicy httpClientPolicy=new HTTPClientPolicy();
httpClientPolicy.setAutoRedirect(true);
http.setClient(httpClientPolicy);
http.setTlsClientParameters(tlsClientParameters);
configureProxy(client);
poltim.sayHi();
assertProxyRequestCount(1);
}
Class: org.apache.cxf.systest.interceptor.InterceptorFaultTest TestCleaner BranchVerifier BooleanVerifier InternalCallVerifier HybridVerifier
@After public void tearDown() throws Exception {
if (null != greeter) {
((java.io.Closeable)greeter).close();
assertTrue("Failed to stop greeter.",control.stopGreeter(null));
greeterBus.shutdown(true);
greeterBus=null;
}
if (null != control) {
assertTrue("Failed to stop greeter",control.stopGreeter(null));
((java.io.Closeable)control).close();
controlBus.shutdown(true);
}
}
UtilityVerifier InternalCallVerifier
@Test public void testRobustFailWithoutAddressingInUserLogicalPhase() throws Exception {
setupGreeter("org/apache/cxf/systest/interceptor/no-addr.xml",false);
control.setRobustInOnlyMode(true);
FaultLocation location=new org.apache.cxf.greeter_control.types.ObjectFactory().createFaultLocation();
location.setPhase("user-logical");
control.setFaultLocation(location);
try {
StringWriter writer=new StringWriter();
((Client)greeter).getInInterceptors().add(new LoggingInInterceptor());
((LoggingInInterceptor)greeterBus.getInInterceptors().get(0)).setPrintWriter(new PrintWriter(writer));
((Client)greeter).getEndpoint().put(Message.ROBUST_ONEWAY,true);
greeter.greetMeOneWay("oneway");
fail("Oneway operation unexpectedly succeded for phase " + location.getPhase());
}
catch ( SOAPFaultException ex) {
}
}
Class: org.apache.cxf.systest.jaxb.MTOMTest APIUtilityVerifier IterativeVerifier InternalCallVerifier EqualityVerifier
@Test public void testMTOMInHashMap() throws Exception {
Service service=Service.create(new QName("http://foo","bar"));
service.addPort(new QName("http://foo","bar"),SOAPBinding.SOAP11HTTP_BINDING,ADDRESS);
MTOMService port=service.getPort(new QName("http://foo","bar"),MTOMService.class);
final int count=99;
ObjectWithHashMapData data=port.getHashMapData(count);
for (int y=1; y < count; y++) {
byte bytes[]=data.getKeyData().get(Integer.toHexString(y));
assertEquals(y,bytes.length);
}
}
Class: org.apache.cxf.systest.jaxb.TestServiceTest InternalCallVerifier EqualityVerifier
@Test public void testExtraSubClassWithJaxb() throws Throwable {
Widget expected=new ExtendedWidget(42,"blah","blah",true,true);
TestService testClient=getTestClient();
Widget widgetFromService=testClient.getWidgetById(42);
Assert.assertEquals(expected,widgetFromService);
}
InternalCallVerifier EqualityVerifier
@Test public void testExtraSubClassWithJaxbFromEndpoint() throws Throwable {
Widget expected=new ExtendedWidget(42,"blah","blah",true,true);
TestService testClient=getTestClient();
((BindingProvider)testClient).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"http://localhost:" + PORT + "/service/TestEndpoint");
Widget widgetFromService=testClient.getWidgetById(42);
Assert.assertEquals(expected,widgetFromService);
}
Class: org.apache.cxf.systest.jaxb.validators.CustomValidatorJAXBTest BooleanVerifier InternalCallVerifier
@Test public void returnNullTest(){
HelloWorld client=(HelloWorld)applicationContext.getBean("testClient",HelloWorld.class);
PassedObject hi=client.returnNull(new PassedObject("John","Doe"));
Assert.assertTrue("Expected: 'Hello null' Actual: '" + hi.getName() + "'","Hello null".equals(hi.getName()));
}
BooleanVerifier InternalCallVerifier
@Test public void sendNullTest(){
HelloWorld client=(HelloWorld)applicationContext.getBean("testClient",HelloWorld.class);
PassedObject hi=client.sayHi(new PassedObject());
Assert.assertTrue("Expected: 'Hello null null' Actual: '" + hi.getName() + "'","Hello null null".equals(hi.getName()));
}
BooleanVerifier InternalCallVerifier
@Test public void cleanTest(){
HelloWorld client=(HelloWorld)applicationContext.getBean("testClient",HelloWorld.class);
PassedObject hi=client.sayHi(new PassedObject("John","Doe"));
Assert.assertTrue("Expected: 'Hello John Doe' Actual: " + hi.getName(),"Hello John Doe".equals(hi.getName()));
}
Class: org.apache.cxf.systest.jaxrs.AbstractJAXRSContinuationsTest InternalCallVerifier EqualityVerifier
@Test public void testImmediateResumeSubresource() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + getPort() + getBaseAddress()+ "/books/subresources/books/resume");
WebClient.getConfig(wc).getHttpConduit().getClient().setReceiveTimeout(1000000L);
wc.accept("text/plain");
String str=wc.get(String.class);
assertEquals("immediateResume",str);
}
InternalCallVerifier EqualityVerifier
@Test public void testUnmappedAfterTimeout() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + getPort() + getBaseAddress()+ "/books/suspend/unmapped");
Response r=wc.get();
assertEquals(500,r.getStatus());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetBookNotFound() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + getPort() + getBaseAddress()+ "/books/notfound");
wc.accept("text/plain");
Response r=wc.get();
assertEquals(404,r.getStatus());
}
InternalCallVerifier EqualityVerifier
@Test public void testDefaultTimeout() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + getPort() + getBaseAddress()+ "/books/defaulttimeout");
WebClient.getConfig(wc).getHttpConduit().getClient().setReceiveTimeout(1000000L);
Response r=wc.get();
assertEquals(503,r.getStatus());
}
InternalCallVerifier EqualityVerifier
@Test public void testImmediateResume() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + getPort() + getBaseAddress()+ "/books/resume");
WebClient.getConfig(wc).getHttpConduit().getClient().setReceiveTimeout(1000000L);
wc.accept("text/plain");
String str=wc.get(String.class);
assertEquals("immediateResume",str);
}
InternalCallVerifier EqualityVerifier
@Test public void testGetBookNotFoundUnmapped() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + getPort() + getBaseAddress()+ "/books/notfound/unmapped");
wc.accept("text/plain");
Response r=wc.get();
assertEquals(500,r.getStatus());
}
Class: org.apache.cxf.systest.jaxrs.JAXRS20ClientServerBookTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testPreMatchContainerFilterThrowsException(){
String address="http://localhost:" + PORT + "/throwException";
WebClient wc=WebClient.create(address);
Response response=wc.get();
assertEquals(500,response.getStatus());
assertEquals("Prematch filter error",response.readEntity(String.class));
assertEquals("prematch",response.getHeaderString("FilterException"));
assertEquals("OK",response.getHeaderString("Response"));
assertEquals("OK2",response.getHeaderString("Response2"));
assertNull(response.getHeaderString("DynamicResponse"));
assertNull(response.getHeaderString("Custom"));
assertEquals("serverWrite",response.getHeaderString("ServerWriterInterceptor"));
assertEquals("serverWrite2",response.getHeaderString("ServerWriterInterceptor2"));
assertEquals("serverWriteHttpResponse",response.getHeaderString("ServerWriterInterceptorHttpResponse"));
assertEquals("text/plain;charset=us-ascii",response.getMediaType().toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetBookWebTargetProvider(){
String address="http://localhost:" + PORT + "/bookstore/bookheaders";
Client client=ClientBuilder.newClient();
client.register(new BookInfoReader());
BookInfo book=client.target(address).path("simple").request("application/xml").get(BookInfo.class);
assertEquals(124L,book.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookAsyncNoCallback() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/bookheaders/simple";
WebClient wc=createWebClient(address);
Future future=wc.async().get(Book.class);
Book book=future.get();
assertEquals(124L,book.getId());
validateResponse(wc);
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testClientFiltersLocalResponse(){
String address="http://localhost:" + PORT + "/bookstores";
List providers=new ArrayList();
providers.add(new ClientCacheRequestFilter());
providers.add(new ClientHeaderResponseFilter());
WebClient wc=WebClient.create(address,providers);
Book theBook=new Book("Echo",123L);
Response r=wc.post(theBook);
assertEquals(201,r.getStatus());
assertEquals("http://localhost/redirect",r.getHeaderString(HttpHeaders.LOCATION));
Book responseBook=r.readEntity(Book.class);
assertSame(theBook,responseBook);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testBookExistsServerStreamReplace() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/books/check2";
WebClient wc=WebClient.create(address);
wc.accept("text/plain").type("text/plain");
assertTrue(wc.post("s",Boolean.class));
}
InternalCallVerifier EqualityVerifier
@Test public void testGetBookSpec(){
String address="http://localhost:" + PORT + "/bookstore/bookheaders/simple";
Client client=ClientBuilder.newClient();
client.register((Object)ClientFilterClientAndConfigCheck.class);
client.property("clientproperty","somevalue");
Book book=client.target(address).request("application/xml").get(Book.class);
assertEquals(124L,book.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookSyncLink(){
String address="http://localhost:" + PORT + "/bookstore/bookheaders/simple";
WebClient wc=createWebClient(address);
Book book=wc.sync().get(Book.class);
assertEquals(124L,book.getId());
validateResponse(wc);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testBookExistsServerAddressOverwrite() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/books/checkN";
WebClient wc=WebClient.create(address);
wc.accept("text/plain").type("text/plain");
assertTrue(wc.post("s",Boolean.class));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testPostBook(){
String address="http://localhost:" + PORT + "/bookstore/bookheaders/simple";
WebClient wc=createWebClientPost(address);
Book book=wc.post(new Book("Book",126L),Book.class);
assertEquals(124L,book.getId());
validatePostResponse(wc,false,false);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testPostMatchContainerFilterThrowsException(){
String address="http://localhost:" + PORT + "/bookstore/bookheaders/simple?throwException";
WebClient wc=WebClient.create(address);
Response response=wc.get();
assertEquals(500,response.getStatus());
assertEquals("Postmatch filter error",response.readEntity(String.class));
assertEquals("postmatch",response.getHeaderString("FilterException"));
assertEquals("OK",response.getHeaderString("Response"));
assertEquals("OK2",response.getHeaderString("Response2"));
assertEquals("Dynamic",response.getHeaderString("DynamicResponse"));
assertEquals("custom",response.getHeaderString("Custom"));
assertEquals("serverWrite",response.getHeaderString("ServerWriterInterceptor"));
assertEquals("text/plain;charset=us-ascii",response.getMediaType().toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetBookSpecProvider(){
String address="http://localhost:" + PORT + "/bookstore/bookheaders/simple";
Client client=ClientBuilder.newClient();
client.register(new BookInfoReader());
WebTarget target=client.target(address);
BookInfo book=target.request("application/xml").get(BookInfo.class);
assertEquals(124L,book.getId());
book=target.request("application/xml").get(BookInfo.class);
assertEquals(124L,book.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testPostBookAsync() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/bookheaders/simple/async";
WebClient wc=createWebClientPost(address);
Future future=wc.async().post(Entity.xml(new Book("Book",126L)),Book.class);
assertEquals(124L,future.get().getId());
validatePostResponse(wc,true,false);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testReplaceBookMistypedCTAndHttpVerb() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/books2/mistyped";
WebClient wc=WebClient.create(endpointAddress,Collections.singletonList(new ReplaceBodyFilter()));
wc.accept("text/mistypedxml").type("text/xml").header("THEMETHOD","PUT");
Book book=wc.invoke("DELETE",new Book("book",555L),Book.class);
assertEquals(561L,book.getId());
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testPostGetCollectionGenericEntityAndType2() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/collections";
WebClient wc=WebClient.create(endpointAddress);
wc.accept("application/xml").type("application/xml");
GenericEntity> collectionEntity=createGenericEntity();
GenericType> genericResponseType=new GenericType>(){
}
;
Future> future=wc.async().post(Entity.entity(collectionEntity,"application/xml"),genericResponseType);
List books2=future.get();
assertNotNull(books2);
List books=collectionEntity.getEntity();
assertNotSame(books,books2);
assertEquals(2,books2.size());
Book b11=books.get(0);
assertEquals(123L,b11.getId());
assertEquals("CXF in Action",b11.getName());
Book b22=books.get(1);
assertEquals(124L,b22.getId());
assertEquals("CXF Rocks",b22.getName());
assertEquals(200,wc.getResponse().getStatus());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testPostBookNewMediaType(){
String address="http://localhost:" + PORT + "/bookstore/bookheaders/simple";
WebClient wc=createWebClientPost(address);
wc.header("newmediatype","application/v1+xml");
Book book=wc.post(new Book("Book",126L),Book.class);
assertEquals(124L,book.getId());
validatePostResponse(wc,false,false);
assertEquals("application/v1+xml",wc.getResponse().getHeaderString("newmediatypeused"));
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testPostGetCollectionGenericEntityAndType3() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/collections";
WebClient wc=WebClient.create(endpointAddress);
wc.accept("application/xml").type("application/xml");
GenericEntity> collectionEntity=createGenericEntity();
GenericType> genericResponseType=new GenericType>(){
}
;
Future future=wc.async().post(Entity.entity(collectionEntity,"application/xml"));
Response r=future.get();
List books2=r.readEntity(genericResponseType);
assertNotNull(books2);
List books=collectionEntity.getEntity();
assertNotSame(books,books2);
assertEquals(2,books2.size());
Book b11=books.get(0);
assertEquals(123L,b11.getId());
assertEquals("CXF in Action",b11.getName());
Book b22=books.get(1);
assertEquals(124L,b22.getId());
assertEquals("CXF Rocks",b22.getName());
assertEquals(200,wc.getResponse().getStatus());
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testPostCollectionGenericEntityGenericCallback() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/collections3";
WebClient wc=WebClient.create(endpointAddress);
wc.accept("application/xml").type("application/xml");
GenericEntity> collectionEntity=createGenericEntity();
final Holder holder=new Holder();
InvocationCallback callback=new GenericInvocationCallback(holder){
}
;
Future future=wc.post(collectionEntity,callback);
Book book=future.get();
assertEquals(200,wc.getResponse().getStatus());
assertSame(book,holder.value);
assertNotSame(collectionEntity.getEntity().get(0),book);
assertEquals(collectionEntity.getEntity().get(0).getName(),book.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testPostEmptyBook(){
String address="http://localhost:" + PORT + "/bookstore/bookheaders/simple";
WebClient wc=createWebClientPost(address);
WebClient.getConfig(wc).getHttpConduit().getClient().setReceiveTimeout(1000000);
Book book=wc.post(null,Book.class);
assertEquals(124L,book.getId());
validatePostResponse(wc,false,true);
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testPostCollectionGenericEntity() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/collections3";
WebClient wc=WebClient.create(endpointAddress);
wc.accept("application/xml").type("application/xml");
GenericEntity> collectionEntity=createGenericEntity();
final Holder holder=new Holder();
InvocationCallback callback=createCallback(holder);
Future future=wc.post(collectionEntity,callback);
Book book=future.get();
assertEquals(200,wc.getResponse().getStatus());
assertSame(book,holder.value);
assertNotSame(collectionEntity.getEntity().get(0),book);
assertEquals(collectionEntity.getEntity().get(0).getName(),book.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testPostReplaceBook() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/books2";
WebClient wc=WebClient.create(endpointAddress,Collections.singletonList(new ReplaceBodyFilter()));
wc.accept("text/xml").type("application/xml");
Book book=wc.post(new Book("book",555L),Book.class);
assertEquals(561L,book.getId());
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testJAXBElementBookCollection() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/jaxbelementxmlrootcollections";
Client client=ClientBuilder.newClient();
WebTarget target=client.target(address);
Book b1=new Book("CXF in Action",123L);
Book b2=new Book("CXF Rocks",124L);
List> books=new ArrayList>();
books.add(new JAXBElement(new QName("bookRootElement"),Book.class,b1));
books.add(new JAXBElement(new QName("bookRootElement"),Book.class,b2));
GenericEntity>> collectionEntity=new GenericEntity>>(books){
}
;
GenericType>> genericResponseType=new GenericType>>(){
}
;
List> books2=target.request().accept("application/xml").post(Entity.entity(collectionEntity,"application/xml"),genericResponseType);
assertNotNull(books2);
assertNotSame(books,books2);
assertEquals(2,books2.size());
Book b11=books.get(0).getValue();
assertEquals(123L,b11.getId());
assertEquals("CXF in Action",b11.getName());
Book b22=books.get(1).getValue();
assertEquals(124L,b22.getId());
assertEquals("CXF Rocks",b22.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testEchoBookElement() throws Exception {
BookStore store=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class);
JAXBElement element=store.echoBookElement(new JAXBElement(new QName("","Book"),Book.class,new Book("CXF",123L)));
Book book=element.getValue();
assertEquals(123L,book.getId());
assertEquals("CXF",book.getName());
Book book2=store.echoBookElement(new Book("CXF3",128L));
assertEquals(130L,book2.getId());
assertEquals("CXF3",book2.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testReplaceBookMistypedCTAndHttpVerb2() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/books2/mistyped";
WebClient wc=WebClient.create(endpointAddress,Collections.singletonList(new ReplaceBodyFilter()));
wc.accept("text/mistypedxml").header("THEMETHOD","PUT");
Book book=wc.invoke("GET",null,Book.class);
assertEquals(561L,book.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testPostReplaceBookMistypedCT() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/books2";
WebClient wc=WebClient.create(endpointAddress,Collections.singletonList(new ReplaceBodyFilter()));
wc.accept("text/mistypedxml").type("text/xml");
Book book=wc.post(new Book("book",555L),Book.class);
assertEquals(561L,book.getId());
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testPostCollectionGenericEntityAsEntity() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/collections3";
WebClient wc=WebClient.create(endpointAddress);
wc.accept("application/xml");
GenericEntity> collectionEntity=createGenericEntity();
final Holder holder=new Holder();
InvocationCallback callback=createCallback(holder);
Future future=wc.async().post(Entity.entity(collectionEntity,"application/xml"),callback);
Book book=future.get();
assertEquals(200,wc.getResponse().getStatus());
assertSame(book,holder.value);
assertNotSame(collectionEntity.getEntity().get(0),book);
assertEquals(collectionEntity.getEntity().get(0).getName(),book.getName());
}
Class: org.apache.cxf.systest.jaxrs.JAXRSAsyncClientTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testPatchBook() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/patch";
WebClient wc=WebClient.create(address);
wc.type("application/xml");
WebClient.getConfig(wc).getRequestContext().put("use.async.http.conduit",true);
Book book=wc.invoke("PATCH",new Book("Patch",123L),Book.class);
assertEquals("Patch",book.getName());
wc.close();
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testRetrieveBookCustomMethodAsync() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/retrieve";
WebClient wc=WebClient.create(address);
wc.accept("application/xml");
Future book=wc.async().method("RETRIEVE",Entity.xml(new Book("Retrieve",123L)),Book.class);
assertEquals("Retrieve",book.get().getName());
wc.close();
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testRetrieveBookCustomMethodAsyncSync() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/retrieve";
WebClient wc=WebClient.create(address);
wc.type("application/xml").accept("application/xml");
Book book=wc.invoke("RETRIEVE",new Book("Retrieve",123L),Book.class);
assertEquals("Retrieve",book.getName());
wc.close();
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testDeleteWithBody() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/deletebody";
WebClient wc=WebClient.create(address);
wc.type("application/xml").accept("application/xml");
WebClient.getConfig(wc).getRequestContext().put("use.async.http.conduit",true);
Book book=wc.invoke("DELETE",new Book("Delete",123L),Book.class);
assertEquals("Delete",book.getName());
wc.close();
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookAsyncResponse404() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/bookheaders/404";
WebClient wc=createWebClient(address);
Future future=wc.async().get(Response.class);
assertEquals(404,future.get().getStatus());
wc.close();
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testPatchBookInputStream() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/patch";
WebClient wc=WebClient.create(address);
wc.type("application/xml");
WebClient.getConfig(wc).getRequestContext().put("use.async.http.conduit",true);
Book book=wc.invoke("PATCH",new ByteArrayInputStream("Patch 123 ".getBytes()),Book.class);
assertEquals("Patch",book.getName());
wc.close();
}
Class: org.apache.cxf.systest.jaxrs.JAXRSAtomBookTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBooks2() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/sub/";
Feed feed=getFeed(endpointAddress,null);
assertEquals("http://localhost:" + PORT + "/bookstore/sub/",feed.getBaseUri().toString());
assertEquals("Collection of Books",feed.getTitle());
getAndCompareJson("http://localhost:" + PORT + "/bookstore/sub/books/entries/123.json","resources/expected_atom_book_json2.txt","*/*");
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBooks() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/bookstore/books/feed";
Feed feed=getFeed(endpointAddress,null);
assertEquals("http://localhost:" + PORT + "/bookstore/bookstore/books/feed",feed.getBaseUri().toString());
assertEquals("Collection of Books",feed.getTitle());
getAndCompareJson("http://localhost:" + PORT + "/bookstore/bookstore/books/feed","resources/expected_atom_books_json.txt","application/json");
getAndCompareJson("http://localhost:" + PORT + "/bookstore/bookstore/books/jsonfeed","resources/expected_atom_books_jsonfeed.txt","application/json, text/html, application/xml;q=0.9," + " application/xhtml+xml, image/png, image/jpeg, image/gif," + " image/x-xbitmap, */*;q=0.1");
Entry entry=addEntry(endpointAddress);
entry=addEntry(endpointAddress + "/relative");
endpointAddress="http://localhost:" + PORT + "/bookstore/bookstore/books/subresources/123";
entry=getEntry(endpointAddress,null);
assertEquals("CXF in Action",entry.getTitle());
getAndCompareJson("http://localhost:" + PORT + "/bookstore/bookstore/books/entries/123","resources/expected_atom_book_json.txt","application/json");
getAndCompareJson("http://localhost:" + PORT + "/bookstore/bookstore/books/entries/123?_type="+ "application/json","resources/expected_atom_book_json.txt","*/*");
getAndCompareJson("http://localhost:" + PORT + "/bookstore/bookstore/books/entries/123?_type="+ "json","resources/expected_atom_book_json.txt","*/*");
getAndCompareJson("http://localhost:" + PORT + "/bookstore/bookstore/books/entries/123.json","resources/expected_atom_book_json.txt","*/*");
getAndCompareJson("http://localhost:" + PORT + "/bookstore/bookstore/books/entries/123.json;a=b","resources/expected_atom_book_json_matrix.txt","*/*");
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBooksWithCustomProvider() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/bookstore4/books/feed";
Feed feed=getFeed(endpointAddress,null);
assertEquals("http://localhost:" + PORT + "/bookstore/bookstore4/books/feed",feed.getBaseUri().toString());
assertEquals("Collection of Books",feed.getTitle());
}
Class: org.apache.cxf.systest.jaxrs.JAXRSClientServerBookTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testPostAnd401WithText() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/post401";
WebClient wc=WebClient.create(endpointAddress);
WebClient.getConfig(wc).getHttpConduit().getClient().setAllowChunking(false);
Response r=wc.post(null);
assertEquals(401,r.getStatus());
assertEquals("This is 401",getStringFromInputStream((InputStream)r.getEntity()));
}
UtilityVerifier BooleanVerifier InternalCallVerifier HybridVerifier
@Test public void testGetBookRelativeUriAutoRedirectNotAllowed() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/redirect/relative?loop=true";
WebClient wc=WebClient.create(address);
WebClient.getConfig(wc).getHttpConduit().getClient().setAutoRedirect(true);
try {
wc.get();
fail("relative Redirect is not allowed");
}
catch ( ProcessingException ex) {
Throwable cause=ex.getCause();
assertTrue(cause.getMessage().contains("Relative Redirect detected on"));
}
}
UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testServerWebApplicationException() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + PORT + "/bookstore/webappexception");
wc.accept("application/xml");
try {
wc.get(Book.class);
fail("Exception expected");
}
catch ( ServerErrorException ex) {
assertEquals(500,ex.getResponse().getStatus());
assertEquals("This is a WebApplicationException",ex.getResponse().readEntity(String.class));
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookRoot() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/;JSESSIONID=xxx";
WebClient wc=WebClient.create(address);
Book book=wc.get(Book.class);
assertEquals(124L,book.getId());
assertEquals("root",book.getName());
}
InternalCallVerifier EqualityVerifier
@Test public void testBookWithSpace() throws Exception {
WebClient client=WebClient.create("http://localhost:" + PORT + "/bookstore/").path("the books/123");
Book book=client.get(Book.class);
assertEquals(123L,book.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testAddBookCustomFailureStatus() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/books/customstatus";
WebClient client=WebClient.create(endpointAddress);
Book book=client.type("text/xml").accept("application/xml").post(new Book(),Book.class);
assertEquals(888L,book.getId());
Response r=client.getResponse();
assertEquals("CustomValue",r.getMetadata().getFirst("CustomHeader"));
assertEquals(233,r.getStatus());
assertEquals("application/xml",r.getMetadata().getFirst("Content-Type"));
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testEmptyPost() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + PORT + "/bookstore/emptypost");
Response response=wc.post(null);
assertEquals(204,response.getStatus());
assertNull(response.getMetadata().getFirst("Content-Type"));
}
BooleanVerifier InternalCallVerifier
@Test public void testBookExistsMalformedMt() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + PORT + "/bookstore/books/check/malformedmt/123");
wc.accept(MediaType.TEXT_PLAIN);
WebClient.getConfig(wc).getInInterceptors().add(new BookServer.ReplaceContentTypeInterceptor());
assertTrue(wc.get(Boolean.class));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testUseMapperOnBus(){
String address="http://localhost:" + PORT + "/bookstore/mapperonbus";
WebClient wc=WebClient.create(address);
Response r=wc.post(null);
assertEquals(500,r.getStatus());
MediaType mt=r.getMediaType();
assertEquals("text/plain;charset=utf-8",mt.toString().toLowerCase());
assertEquals("the-mapper",r.getHeaderString("BusMapper"));
assertEquals("BusMapperException",r.readEntity(String.class));
}
UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testServerWebApplicationExceptionXML() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + PORT + "/bookstore/webappexceptionXML");
wc.accept("application/xml");
try {
wc.get(Book.class);
fail("Exception expected");
}
catch ( NotAcceptableException ex) {
assertEquals(406,ex.getResponse().getStatus());
Book exBook=ex.getResponse().readEntity(Book.class);
assertEquals("Exception",exBook.getName());
assertEquals(999L,exBook.getId());
}
}
APIUtilityVerifier IterativeVerifier InternalCallVerifier EqualityVerifier
@Test public void testBadlyQuotedHeaders() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/badlyquotedheaders";
String[] responses=new String[]{"\"some text","\"some text, some more text with inlined \"","\"some te\\"};
for (int i=0; i < 3; i++) {
WebClient wc=WebClient.create(endpointAddress);
WebClient.getConfig(wc).getRequestContext().put("org.apache.cxf.http.header.split",true);
Response r=wc.query("type",Integer.toString(i)).get();
assertEquals(responses[i],r.getMetadata().get("SomeHeader" + i).get(0));
}
WebClient wc=WebClient.create(endpointAddress);
WebClient.getConfig(wc).getRequestContext().put("org.apache.cxf.http.header.split",true);
Response r3=wc.query("type","3").get();
List r3values=r3.getMetadata().get("SomeHeader3");
assertEquals(4,r3values.size());
assertEquals("some text",r3values.get(0));
assertEquals("\"other quoted\"",r3values.get(1));
assertEquals("text",r3values.get(2));
assertEquals("blah",r3values.get(3));
}
InternalCallVerifier EqualityVerifier
@Test public void testUpdateBook() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/books";
File input=new File(getClass().getResource("resources/update_book.txt").toURI());
PutMethod put=new PutMethod(endpointAddress);
RequestEntity entity=new FileRequestEntity(input,"text/xml; charset=ISO-8859-1");
put.setRequestEntity(entity);
HttpClient httpclient=new HttpClient();
try {
int result=httpclient.executeMethod(put);
assertEquals(200,result);
InputStream expected=getClass().getResourceAsStream("resources/expected_update_book.txt");
assertEquals(stripXmlInstructionIfNeeded(getStringFromInputStream(expected)),stripXmlInstructionIfNeeded(getStringFromInputStream(put.getResponseBodyAsStream())));
}
finally {
put.releaseConnection();
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testUpdateBookWithProxy() throws Exception {
String address="http://localhost:" + PORT;
BookStore store=JAXRSClientFactory.create(address,BookStore.class);
Book b=store.updateEchoBook(new Book("CXF",125L));
assertEquals(125L,b.getId());
}
BooleanVerifier InternalCallVerifier
@Test public void testBookExistsWebClientPrimitiveBoolean() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + PORT + "/bookstore/books/check/123");
wc.accept("text/plain");
assertTrue(wc.get(boolean.class));
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testPostCollectionOfBooksWebClient() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/collections";
WebClient wc=WebClient.create(endpointAddress);
wc.accept("application/xml").type("application/xml");
Book b1=new Book("CXF in Action",123L);
Book b2=new Book("CXF Rocks",124L);
List books=new ArrayList();
books.add(b1);
books.add(b2);
List books2=new ArrayList(wc.postAndGetCollection(books,Book.class,Book.class));
assertNotNull(books2);
assertNotSame(books,books2);
assertEquals(2,books2.size());
Book b11=books.get(0);
assertEquals(123L,b11.getId());
assertEquals("CXF in Action",b11.getName());
Book b22=books.get(1);
assertEquals(124L,b22.getId());
assertEquals("CXF Rocks",b22.getName());
assertEquals(200,wc.getResponse().getStatus());
}
InternalCallVerifier EqualityVerifier
@SuppressWarnings("deprecation") @Test public void testGetPlainLong() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/booksplain";
PostMethod post=new PostMethod(endpointAddress);
post.addRequestHeader("Content-Type","text/plain");
post.addRequestHeader("Accept","text/plain");
post.setRequestBody("12345");
HttpClient httpclient=new HttpClient();
try {
int result=httpclient.executeMethod(post);
assertEquals(200,result);
assertEquals(post.getResponseBodyAsString(),"12345");
}
finally {
post.releaseConnection();
}
}
InternalCallVerifier EqualityVerifier
@Test public void testEmptyPostProxy() throws Exception {
BookStore store=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class);
store.emptypost();
assertEquals(204,WebClient.client(store).getResponse().getStatus());
}
UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testServerWebApplicationExceptionWithProxy() throws Exception {
BookStore store=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class);
try {
store.throwException();
fail("Exception expected");
}
catch ( ServerErrorException ex) {
assertEquals(500,ex.getResponse().getStatus());
assertEquals("This is a WebApplicationException",ex.getResponse().readEntity(String.class));
}
}
InternalCallVerifier EqualityVerifier
@Test public void testProxyBeanParam() throws Exception {
BookStore store=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class);
BookStore.BookBean bean=new BookStore.BookBean();
bean.setId(100L);
bean.setId2(23L);
BookStore.BookBeanNested nested=new BookStore.BookBeanNested();
nested.setId4(123);
bean.setNested(nested);
Book book=store.getBeanParamBook(bean);
assertEquals(123L,book.getId());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testEmptyPostBytes() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + PORT + "/bookstore/emptypost");
Response response=wc.post(new byte[]{});
assertEquals(204,response.getStatus());
assertNull(response.getMetadata().getFirst("Content-Type"));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetHeadBook123WebClient2() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/getheadbook/";
WebClient client=WebClient.create(address);
Book b=client.get(Book.class);
assertEquals(b.getId(),123L);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testCapturedServerInFault() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/infault";
WebClient wc=WebClient.create(endpointAddress);
Response r=wc.get();
assertEquals(401,r.getStatus());
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testPostCollectionGenericEntityWebClient() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/collections3";
WebClient wc=WebClient.create(endpointAddress);
wc.accept("application/xml").type("application/xml");
Book b1=new Book("CXF in Action",123L);
Book b2=new Book("CXF Rocks",124L);
List books=new ArrayList();
books.add(b1);
books.add(b2);
GenericEntity> genericCollectionEntity=new GenericEntity>(books){
}
;
Book book=wc.post(genericCollectionEntity,Book.class);
assertEquals(200,wc.getResponse().getStatus());
assertNotSame(b1,book);
assertEquals(b1.getName(),book.getName());
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testBookWithSpaceProxyWithBufferedStream() throws Exception {
BookStore store=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class);
WebClient.getConfig(store).getResponseContext().put("buffer.proxy.response","true");
Book book=store.getBookWithSpace("123");
assertEquals(123L,book.getId());
assertTrue(WebClient.client(store).getResponse().readEntity(String.class).contains("
InternalCallVerifier EqualityVerifier
@Test public void testOnewayProxy() throws Exception {
BookStore proxy=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class);
proxy.onewayRequest();
assertEquals(202,WebClient.client(proxy).getResponse().getStatus());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetBookAdapterInfoProxy() throws Exception {
BookStore store=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class);
BookInfo info=store.getBookAdapter();
assertEquals(123L,info.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetCustomBookText(){
String address="http://localhost:" + PORT + "/bookstore/customtext";
WebClient wc=WebClient.create(address);
Response r=wc.accept("text/custom").get();
String name=r.readEntity(String.class);
assertEquals("Good book",name);
assertEquals("text/custom;charset=us-ascii",r.getMediaType().toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testProxyBeanParam2() throws Exception {
BookStore store=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class);
WebClient.getConfig(store).getHttpConduit().getClient().setReceiveTimeout(10000000L);
BookStore.BookBean2 bean=new BookStore.BookBean2();
bean.setId(100L);
bean.setId2(23L);
BookStore.BookBeanNested nested=new BookStore.BookBeanNested();
nested.setId4(123);
Book book=store.getTwoBeanParamsBook(bean,nested);
assertEquals(123L,book.getId());
}
InternalCallVerifier IdentityVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetBookArray() throws Exception {
BookStore store=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class);
Book b1=new Book("CXF in Action",123L);
Book b2=new Book("CXF Rocks",124L);
Book[] books=new Book[2];
books[0]=b1;
books[1]=b2;
Book[] books2=store.getBookArray(books);
assertNotNull(books2);
assertNotSame(books,books2);
assertEquals(2,books2.length);
Book b11=books2[0];
assertEquals(123L,b11.getId());
assertEquals("CXF in Action",b11.getName());
Book b22=books2[1];
assertEquals(124L,b22.getId());
assertEquals("CXF Rocks",b22.getName());
}
InternalCallVerifier EqualityVerifier
@Test public void testCreatePutWithProxy() throws Exception {
BookStore bs=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class);
Response r=bs.createBook(777L);
assertEquals(200,r.getStatus());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testBlockAndTrowException() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/blockAndThrowException";
WebClient wc=WebClient.create(address);
Response r=wc.get();
assertEquals(500,r.getStatus());
}
InternalCallVerifier EqualityVerifier
@Test public void testProxyWithCollectionMatrixParams() throws Exception {
BookStore proxy=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class);
List params=new ArrayList();
params.add("12");
params.add("3");
Book book=proxy.getBookByMatrixListParams(params);
assertEquals(123L,book.getId());
}
InternalCallVerifier EqualityVerifier
@Test public void testEchoBookName202() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + PORT + "/bookstore/booksecho202");
wc.type("text/plain").accept("text/plain");
Response r=wc.post("book");
assertEquals(202,r.getStatus());
assertEquals("book",r.readEntity(String.class));
}
UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testServerWebApplicationExceptionResponse() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + PORT + "/bookstore/webappexception");
wc.accept("application/xml");
try {
Response r=wc.get(Response.class);
assertEquals(500,r.getStatus());
}
catch ( WebApplicationException ex) {
fail("Unexpected exception");
}
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testPostCollectionGetBooksWebClient() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/collections3";
WebClient wc=WebClient.create(endpointAddress);
wc.accept("application/xml").type("application/xml");
Book b1=new Book("CXF in Action",123L);
Book b2=new Book("CXF Rocks",124L);
List books=new ArrayList();
books.add(b1);
books.add(b2);
Book book=wc.postCollection(books,Book.class,Book.class);
assertEquals(200,wc.getResponse().getStatus());
assertNotSame(b1,book);
assertEquals(b1.getName(),book.getName());
}
InternalCallVerifier EqualityVerifier
@Test public void testConsumeTypeMismatch() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/unsupportedcontenttype";
PostMethod post=new PostMethod(endpointAddress);
post.setRequestHeader("Content-Type","application/bar");
post.setRequestHeader("Accept","text/xml");
HttpClient httpclient=new HttpClient();
try {
int result=httpclient.executeMethod(post);
assertEquals(415,result);
}
finally {
post.releaseConnection();
}
}
InternalCallVerifier EqualityVerifier
@SuppressWarnings("deprecation") @Test public void testNoMessageReaderFound() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/binarybooks";
PostMethod post=new PostMethod(endpointAddress);
post.setRequestHeader("Content-Type","application/octet-stream");
post.setRequestHeader("Accept","text/xml");
post.setRequestBody("Bar");
HttpClient httpclient=new HttpClient();
try {
int result=httpclient.executeMethod(post);
assertEquals(415,result);
}
finally {
post.releaseConnection();
}
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testOnewayWebClient() throws Exception {
WebClient client=WebClient.create("http://localhost:" + PORT + "/bookstore/oneway");
Response r=client.header("OnewayRequest","true").post(null);
assertEquals(202,r.getStatus());
assertFalse(r.getHeaders().isEmpty());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookWithColonMarks() throws Exception {
String endpointAddressUrlEncoded="http://localhost:" + PORT + "/bookstore/books/colon/"+ URLEncoder.encode("1:2:3",StandardCharsets.UTF_8.name());
Response r=WebClient.create(endpointAddressUrlEncoded).get();
assertEquals(404,r.getStatus());
String endpointAddress="http://localhost:" + PORT + "/bookstore/books/colon/1:2:3";
WebClient wc=WebClient.create(endpointAddress);
Book b=wc.get(Book.class);
assertEquals(123L,b.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookByHeaderPerRequestConstructorFault() throws Exception {
String address="http://localhost:" + PORT + "/bookstore2/bookheaders";
WebClient wc=WebClient.create(address);
wc.accept("application/xml");
wc.header("BOOK","1","2","4");
Response r=wc.get();
assertEquals(400,r.getStatus());
assertEquals("Constructor: Header value 3 is required",r.readEntity(String.class));
}
BooleanVerifier InternalCallVerifier
@Test public void testFormattedJSON(){
WebClient wc=WebClient.create("http://localhost:" + PORT + "/bookstore/books/123");
wc.accept("application/json");
String response=wc.get(String.class);
assertTrue(response.startsWith("{"));
assertTrue(response.endsWith("}"));
assertTrue(response.contains("\"Book\":{"));
assertTrue(response.indexOf("\"Book\":{") == 1);
wc.query("_format","");
response=wc.get(String.class);
assertTrue(response.startsWith("{"));
assertTrue(response.endsWith("}"));
assertTrue(response.contains("\"Book\":{"));
assertFalse(response.indexOf("\"Book\":{") == 1);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookQueryDefault() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/books/query/default";
WebClient wc=WebClient.create(address);
Response r=wc.get();
Book book=r.readEntity(Book.class);
assertEquals(123L,book.getId());
}
InternalCallVerifier EqualityVerifier
@Test public void testUpdateBookFailed() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/books";
File input=new File(getClass().getResource("resources/update_book_not_exist.txt").toURI());
PutMethod post=new PutMethod(endpointAddress);
RequestEntity entity=new FileRequestEntity(input,"text/xml; charset=ISO-8859-1");
post.setRequestEntity(entity);
HttpClient httpclient=new HttpClient();
try {
int result=httpclient.executeMethod(post);
assertEquals(304,result);
}
finally {
post.releaseConnection();
}
}
UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testServerWebApplicationExceptionXMLWithProxy() throws Exception {
BookStore proxy=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class);
try {
proxy.throwExceptionXML();
fail("Exception expected");
}
catch ( NotAcceptableException ex) {
assertEquals(406,ex.getResponse().getStatus());
Book exBook=ex.getResponse().readEntity(Book.class);
assertEquals("Exception",exBook.getName());
assertEquals(999L,exBook.getId());
}
}
InternalCallVerifier EqualityVerifier
@Test public void testWithComplexPath(){
WebClient wc=WebClient.create("http://localhost:" + PORT + "/bookstore/allCharsButA-B/:@!$&'()*+,;=-._~");
wc.accept("application/xml");
Book book=wc.get(Book.class);
assertEquals("Encoded Path",book.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testStatusAngHeadersFromStream() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/books/statusFromStream";
WebClient wc=WebClient.create(address);
wc.accept("text/xml");
Response r=wc.get();
assertEquals(503,r.getStatus());
assertEquals("text/custom+plain",r.getMediaType().toString());
assertEquals("CustomValue",r.getHeaderString("CustomHeader"));
assertEquals("Response is not available",r.readEntity(String.class));
}
UtilityVerifier BooleanVerifier InternalCallVerifier HybridVerifier
@Test public void testGetBookRelativeUriAutoRedirectLoop() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/redirect/relative?loop=true";
WebClient wc=WebClient.create(address);
WebClient.getConfig(wc).getRequestContext().put("http.redirect.relative.uri","true");
WebClient.getConfig(wc).getHttpConduit().getClient().setAutoRedirect(true);
try {
wc.get();
fail("Redirect loop must be detected");
}
catch ( ProcessingException ex) {
Throwable cause=ex.getCause();
assertTrue(cause.getMessage().contains("Redirect loop detected on"));
}
}
InternalCallVerifier EqualityVerifier
@Test public void testGetStringList() throws Exception {
String address="http://localhost:" + PORT;
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
bean.setProvider(new BookStore.StringListBodyReaderWriter());
bean.setAddress(address);
bean.setResourceClass(BookStore.class);
BookStore store=bean.create(BookStore.class);
List str=store.getBookListArray();
assertEquals("Good book",str.get(0));
}
InternalCallVerifier EqualityVerifier
@Test public void testGetPrimitiveIntArray() throws Exception {
String address="http://localhost:" + PORT;
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
bean.setProvider(new BookStore.PrimitiveIntArrayReaderWriter());
bean.setAddress(address);
bean.setResourceClass(BookStore.class);
BookStore store=bean.create(BookStore.class);
int[] arr=store.getBookIndexAsIntArray();
assertEquals(3,arr.length);
assertEquals(1,arr[0]);
assertEquals(2,arr[1]);
assertEquals(3,arr[2]);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testEchoXmlBookQuery() throws Exception {
String address="http://localhost:" + PORT;
BookStore store=JAXRSClientFactory.create(address,BookStore.class,Collections.singletonList(new BookServer.ParamConverterImpl()));
Book b=store.echoXmlBookQuery(new Book("query",125L),(byte)125);
assertEquals(125L,b.getId());
assertEquals("query",b.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetSearchBookSQL() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/books/querycontext/id=ge=123";
WebClient client=WebClient.create(address);
client.accept("text/plain");
String sql=client.get(String.class);
assertEquals("SELECT * FROM books WHERE id >= '123'",sql);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetCollectionOfBooks() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/collections";
WebClient wc=WebClient.create(endpointAddress);
wc.accept("application/xml");
Collection extends Book> collection=wc.getCollection(Book.class);
assertEquals(1,collection.size());
Book book=collection.iterator().next();
assertEquals(123L,book.getId());
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetBookCollection() throws Exception {
BookStore store=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class);
Book b1=new Book("CXF in Action",123L);
Book b2=new Book("CXF Rocks",124L);
List books=new ArrayList();
books.add(b1);
books.add(b2);
List books2=store.getBookCollection(books);
assertNotNull(books2);
assertNotSame(books,books2);
assertEquals(2,books2.size());
Book b11=books2.get(0);
assertEquals(123L,b11.getId());
assertEquals("CXF in Action",b11.getName());
Book b22=books2.get(1);
assertEquals(124L,b22.getId());
assertEquals("CXF Rocks",b22.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookSameUriAutoRedirect() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/redirect?sameuri=true";
WebClient wc=WebClient.create(address);
WebClient.getConfig(wc).getHttpConduit().getClient().setAutoRedirect(true);
WebClient.getConfig(wc).getRequestContext().put(org.apache.cxf.message.Message.MAINTAIN_SESSION,Boolean.TRUE);
Response r=wc.get();
Book book=r.readEntity(Book.class);
assertEquals(123L,book.getId());
String requestUri=r.getStringHeaders().getFirst("RequestURI");
assertEquals("http://localhost:" + PORT + "/bookstore/redirect?redirect=true",requestUri);
String theCookie=r.getStringHeaders().getFirst("TheCookie");
assertEquals("b",theCookie);
}
InternalCallVerifier EqualityVerifier
@Test public void testGetPrimitiveDoubleArray() throws Exception {
String address="http://localhost:" + PORT;
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
bean.setProvider(new BookStore.PrimitiveDoubleArrayReaderWriter());
bean.setAddress(address);
bean.setResourceClass(BookStore.class);
BookStore store=bean.create(BookStore.class);
double[] arr=store.getBookIndexAsDoubleArray();
assertEquals(3,arr.length);
assertEquals(1,arr[0],0.0);
assertEquals(2,arr[1],0.0);
assertEquals(3,arr[2],0.0);
}
InternalCallVerifier EqualityVerifier
@Test public void testEchoBookElementWebClient() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + PORT + "/bookstore/books/element/echo");
wc.type("application/xml").accept("application/xml");
Book book=wc.post(new Book("CXF",123L),Book.class);
assertEquals(123L,book.getId());
assertEquals("CXF",book.getName());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testTempRedirectWebClient() throws Exception {
WebClient client=WebClient.create("http://localhost:" + PORT + "/bookstore/tempredirect");
Response r=client.type("*/*").get();
assertEquals(307,r.getStatus());
MultivaluedMap map=r.getMetadata();
assertEquals("http://localhost:" + PORT + "/whatever/redirection?css1=http%3A//bar",map.getFirst("Location").toString());
List cookies=r.getMetadata().get("Set-Cookie");
assertNotNull(cookies);
assertEquals(2,cookies.size());
}
InternalCallVerifier EqualityVerifier
@Test public void testDeleteWithProxy() throws Exception {
BookStore bs=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class);
Response r=bs.deleteBook("123");
assertEquals(200,r.getStatus());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testWebClientUnwrapBookWithXslt() throws Exception {
XSLTJaxbProvider provider=new XSLTJaxbProvider();
provider.setInTemplate("classpath:/org/apache/cxf/systest/jaxrs/resources/unwrapbook.xsl");
WebClient wc=WebClient.create("http://localhost:" + PORT + "/bookstore/books/wrapper",Collections.singletonList(provider));
wc.path("{id}",123);
Book book=wc.get(Book.class);
assertNotNull(book);
assertEquals(123L,book.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testPostNullGetEmptyCollectionProxy() throws Exception {
String endpointAddress="http://localhost:" + PORT;
BookStore bs=JAXRSClientFactory.create(endpointAddress,BookStore.class);
List books=bs.postBookGetCollection(null);
assertNotNull(books);
assertEquals(0,books.size());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testPostObjectGetCollection() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/collectionBook";
WebClient wc=WebClient.create(endpointAddress);
wc.accept("application/xml").type("application/xml");
Book b1=new Book("Book",666L);
List books=new ArrayList(wc.postObjectGetCollection(b1,Book.class));
assertNotNull(books);
assertEquals(1,books.size());
Book b=books.get(0);
assertEquals(666L,b.getId());
assertEquals("Book",b.getName());
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testHeadBookByURL() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + PORT + "/bookstore/bookurl/http%3A%2F%2Ftest.com%2Frss%2F123");
Response response=wc.head();
assertTrue(response.getMetadata().size() != 0);
assertEquals(0,((InputStream)response.getEntity()).available());
}
InternalCallVerifier EqualityVerifier
@Test public void testDeleteBook() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/books/123";
DeleteMethod post=new DeleteMethod(endpointAddress);
HttpClient httpclient=new HttpClient();
try {
int result=httpclient.executeMethod(post);
assertEquals(200,result);
}
finally {
post.releaseConnection();
}
}
InternalCallVerifier EqualityVerifier
@Test public void testMalformedAcceptType(){
WebClient wc=WebClient.create("http://localhost:" + PORT + "/bookstore/books/123");
wc.accept("application");
Response r=wc.get();
assertEquals(406,r.getStatus());
}
InternalCallVerifier EqualityVerifier
@Test public void testEmptyPostProxy2() throws Exception {
String address="http://localhost:" + PORT;
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
bean.setAddress(address);
bean.setResourceClass(BookStore.class);
BookStore store=bean.create(BookStore.class);
store.emptypostNoPath();
assertEquals(204,WebClient.client(store).getResponse().getStatus());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testSearchBook123WithWebClient() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/books/search";
WebClient client=WebClient.create(address);
Book b=client.query("_s","name==CXF*;id=ge=123;id=lt=124").get(Book.class);
assertEquals(b.getId(),123L);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookWithNameInQuery() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/name-in-query";
WebClient wc=WebClient.create(endpointAddress);
String name="Many spaces";
wc.query("name",name);
Book b=wc.get(Book.class);
assertEquals(name,b.getName());
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testGetCDs() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + PORT + "/bookstore/cds");
CDs cds=wc.get(CDs.class);
Collection collection=cds.getCD();
assertEquals(2,collection.size());
assertTrue(collection.contains(new CD("BICYCLE RACE",124)));
assertTrue(collection.contains(new CD("BOHEMIAN RHAPSODY",123)));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetCustomBookResponse(){
String address="http://localhost:" + PORT + "/bookstore/customresponse";
WebClient wc=WebClient.create(address);
Response r=wc.accept("application/xml").get(Response.class);
Book book=r.readEntity(Book.class);
assertEquals(222L,book.getId());
assertEquals("OK",r.getHeaderString("customresponse"));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testUpdateBookWithDom() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/bookswithdom";
File input=new File(getClass().getResource("resources/update_book.txt").toURI());
PutMethod put=new PutMethod(endpointAddress);
RequestEntity entity=new FileRequestEntity(input,"text/xml; charset=ISO-8859-1");
put.setRequestEntity(entity);
HttpClient httpclient=new HttpClient();
try {
int result=httpclient.executeMethod(put);
assertEquals(200,result);
String resp=put.getResponseBodyAsString();
InputStream expected=getClass().getResourceAsStream("resources/update_book.txt");
String s=getStringFromInputStream(expected);
assertTrue(resp.indexOf(s) >= 0);
}
finally {
put.releaseConnection();
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testGetCustomBookBufferedResponse(){
String address="http://localhost:" + PORT + "/bookstore/customresponse";
WebClient wc=WebClient.create(address);
Response r=wc.accept("application/xml").get(Response.class);
r.bufferEntity();
String bookStr=r.readEntity(String.class);
assertTrue(bookStr.endsWith(""));
Book book=r.readEntity(Book.class);
assertEquals(222L,book.getId());
assertEquals("OK",r.getHeaderString("customresponse"));
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testAddBookProxyResponse(){
BookStore store=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class);
Book b=new Book("CXF rocks",123L);
Response r=store.addBook(b);
assertNotNull(r);
InputStream is=(InputStream)r.getEntity();
assertNotNull(is);
XMLSource source=new XMLSource(is);
source.setBuffering();
assertEquals(124L,Long.parseLong(source.getValue("Book/id")));
assertEquals("CXF rocks",source.getValue("Book/name"));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookFromResponseWithWebClientAndReader() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/genericresponse/123";
WebClient wc=WebClient.create(address);
Response r=wc.accept("application/xml").get();
assertEquals(200,r.getStatus());
Book book=r.readEntity(Book.class);
assertEquals(123L,book.getId());
}
InternalCallVerifier EqualityVerifier
@Test public void testEmptyPutProxy() throws Exception {
BookStore store=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class);
store.emptyput();
assertEquals(204,WebClient.client(store).getResponse().getStatus());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testEchoBookElementWildcard() throws Exception {
BookStore store=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class);
JAXBElement super Book> element=store.echoBookElementWildcard(new JAXBElement(new QName("","Book"),Book.class,new Book("CXF",123L)));
Book book=(Book)element.getValue();
assertEquals(123L,book.getId());
assertEquals("CXF",book.getName());
}
InternalCallVerifier EqualityVerifier
@Test public void testUpdateWithProxy() throws Exception {
BookStore bs=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class);
Book book=new Book();
book.setId(888);
bs.updateBook(book);
assertEquals(304,WebClient.client(bs).getResponse().getStatus());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testQuotedHeaders() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/quotedheaders";
WebClient wc=WebClient.create(endpointAddress);
WebClient.getConfig(wc).getRequestContext().put("org.apache.cxf.http.header.split",true);
Response r=wc.get();
List header1=r.getMetadata().get("SomeHeader1");
assertEquals(1,header1.size());
assertEquals("\"some text, some more text\"",header1.get(0));
List header2=r.getMetadata().get("SomeHeader2");
assertEquals(3,header2.size());
assertEquals("\"some text\"",header2.get(0));
assertEquals("\"quoted,text\"",header2.get(1));
assertEquals("\"even more text\"",header2.get(2));
List header3=r.getMetadata().get("SomeHeader3");
assertEquals(1,header3.size());
assertEquals("\"some text, some more text with inlined \"\"",header3.get(0));
List header4=r.getMetadata().get("SomeHeader4");
assertEquals(1,header4.size());
assertEquals("\"\"",header4.get(0));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookAcceptWildcard() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/books/wildcard";
WebClient wc=WebClient.create(address);
Response r=wc.accept("text/*").get();
assertEquals(406,r.getStatus());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetBookLowCaseHeader() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + PORT + "/bookstore/booksecho3");
wc.type("text/plain").accept("text/plain").header("CustomHeader","custom");
String name=wc.post("book",String.class);
assertEquals("book",name);
assertEquals("custom",wc.getResponse().getHeaderString("CustomHeader"));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testPropogateException() throws Exception {
GetMethod get=new GetMethod("http://localhost:" + PORT + "/bookstore/propagate-exception");
get.setRequestHeader("Accept","application/xml");
get.addRequestHeader("Cookie","a=b;c=d");
get.addRequestHeader("Cookie","e=f");
get.setRequestHeader("Accept-Language","da;q=0.8,en");
get.setRequestHeader("Book","1,2,3");
HttpClient httpClient=new HttpClient();
try {
int result=httpClient.executeMethod(get);
assertEquals(500,result);
String content=getStringFromInputStream(get.getResponseBodyAsStream());
assertTrue(content.contains("Error") && content.contains("500"));
}
finally {
get.releaseConnection();
}
}
InternalCallVerifier EqualityVerifier
@Test public void testGetBookFromResponseWithProxyAndReader() throws Exception {
BookStore bs=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class);
Response r=bs.getGenericResponseBook("123");
assertEquals(200,r.getStatus());
Book book=r.readEntity(Book.class);
assertEquals(123L,book.getId());
}
UtilityVerifier BooleanVerifier InternalCallVerifier HybridVerifier
@Test public void testGetBookDiffUriAutoRedirect() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/redirect?sameuri=false";
WebClient wc=WebClient.create(address);
WebClient.getConfig(wc).getRequestContext().put("http.redirect.same.host.only","true");
WebClient.getConfig(wc).getHttpConduit().getClient().setAutoRedirect(true);
try {
wc.get();
fail("Redirect to different host is not allowed");
}
catch ( ProcessingException ex) {
Throwable cause=ex.getCause();
assertTrue(cause.getMessage().contains("Different HTTP Scheme or Host Redirect detected on"));
}
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testGetCDsJSON() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/cds";
GetMethod get=new GetMethod(endpointAddress);
get.addRequestHeader("Accept","application/json");
HttpClient httpclient=new HttpClient();
try {
int result=httpclient.executeMethod(get);
assertEquals(200,result);
InputStream expected123=getClass().getResourceAsStream("resources/expected_get_cdsjson123.txt");
InputStream expected124=getClass().getResourceAsStream("resources/expected_get_cdsjson124.txt");
assertTrue(get.getResponseBodyAsString().indexOf(getStringFromInputStream(expected123)) >= 0);
assertTrue(get.getResponseBodyAsString().indexOf(getStringFromInputStream(expected124)) >= 0);
}
finally {
get.releaseConnection();
}
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetJAXBElementXmlRootBookCollection() throws Exception {
BookStore store=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class);
Book b1=new Book("CXF in Action",123L);
Book b2=new Book("CXF Rocks",124L);
List> books=new ArrayList>();
books.add(new JAXBElement(new QName("bookRootElement"),Book.class,b1));
books.add(new JAXBElement(new QName("bookRootElement"),Book.class,b2));
List> books2=store.getJAXBElementBookXmlRootCollection(books);
assertNotNull(books2);
assertNotSame(books,books2);
assertEquals(2,books2.size());
Book b11=books2.get(0).getValue();
assertEquals(123L,b11.getId());
assertEquals("CXF in Action",b11.getName());
Book b22=books2.get(1).getValue();
assertEquals(124L,b22.getId());
assertEquals("CXF Rocks",b22.getName());
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testExplicitOptionsNoSplitByDefault() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + PORT + "/bookstore/options");
Response response=wc.options();
List values=Arrays.asList(response.getHeaderString("Allow").split(","));
assertNotNull(values);
assertTrue(values.contains("POST") && values.contains("GET") && values.contains("DELETE")&& values.contains("PUT"));
assertEquals(0,((InputStream)response.getEntity()).available());
List date=response.getMetadata().get("Date");
assertNotNull(date);
assertEquals(1,date.size());
}
BooleanVerifier InternalCallVerifier
@Test public void testBookExists2() throws Exception {
BookStore proxy=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class);
assertTrue(proxy.checkBook2(123L));
assertFalse(proxy.checkBook2(125L));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testProcessingInstruction() throws Exception {
String base="http://localhost:" + PORT;
String endpointAddress=base + "/bookstore/name-in-query";
WebClient wc=WebClient.create(endpointAddress);
String name="Many spaces";
wc.query("name",name);
String content=wc.get(String.class);
assertTrue(content.contains(""));
assertTrue(content.contains(""));
assertTrue(content.contains("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""));
assertTrue(content.contains("xsi:schemaLocation=\"" + base + "/book.xsd\""));
}
UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testServerWebApplicationExceptionWithProxy2() throws Exception {
BookStore store=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class);
try {
store.throwException();
fail("Exception expected");
}
catch ( WebApplicationException ex) {
assertEquals(500,ex.getResponse().getStatus());
assertEquals("This is a WebApplicationException",ex.getResponse().readEntity(String.class));
}
}
InternalCallVerifier EqualityVerifier
@Test public void testGetBookAdapterInterfaceProxy() throws Exception {
BookStore store=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class);
BookInfoInterface info=store.getBookAdapterInterface();
assertEquals(123L,info.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookAsObject() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/object";
WebClient wc=WebClient.create(endpointAddress);
Book b=wc.get(Book.class);
assertEquals("Book as Object",b.getName());
}
BooleanVerifier InternalCallVerifier
@Test public void testBookExistsWebClientBooleanObject() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + PORT + "/bookstore/books/check/123");
wc.accept("text/plain");
assertTrue(wc.get(Boolean.class));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookByHeaderPerRequestInjectedFault() throws Exception {
String address="http://localhost:" + PORT + "/bookstore2/bookheaders/injected";
WebClient wc=WebClient.create(address);
wc.accept("application/xml");
wc.header("BOOK","2","3");
Response r=wc.get();
assertEquals(400,r.getStatus());
assertEquals("Param setter: 3 header values are required",r.readEntity(String.class));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetBookNameAsByteArray(){
String address="http://localhost:" + PORT + "/bookstore/booknames/123";
WebClient wc=WebClient.create(address);
Response r=wc.accept("application/bar").get();
String name=r.readEntity(String.class);
assertEquals("CXF in Action",name);
String lengthStr=r.getHeaderString(HttpHeaders.CONTENT_LENGTH);
assertNotNull(lengthStr);
long length=Long.valueOf(lengthStr);
assertEquals(name.length(),length);
}
InternalCallVerifier EqualityVerifier
@Test public void testGetStringArray() throws Exception {
String address="http://localhost:" + PORT;
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
bean.setProvider(new BookStore.StringArrayBodyReaderWriter());
bean.setAddress(address);
bean.setResourceClass(BookStore.class);
BookStore store=bean.create(BookStore.class);
String[] str=store.getBookStringArray();
assertEquals("Good book",str[0]);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testPostEmptyForm() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/emptyform";
WebClient wc=WebClient.create(address);
Response r=wc.form(new Form());
assertEquals("empty form",r.readEntity(String.class));
}
InternalCallVerifier EqualityVerifier
@Test public void testGetBookSimple222() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + PORT + "/simplebooks/222");
Book book=wc.get(Book.class);
assertEquals(222L,book.getId());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetBookSimple() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + PORT + "/simplebooks/simple");
Book book=wc.get(Book.class);
assertEquals(444L,book.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testPostEmptyFormAsInStream() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/emptyform";
WebClient wc=WebClient.create(address);
WebClient.getConfig(wc).getRequestContext().put("org.apache.cxf.empty.request",true);
wc.type(MediaType.APPLICATION_FORM_URLENCODED);
Response r=wc.post(new ByteArrayInputStream("".getBytes()));
assertEquals("empty form",r.readEntity(String.class));
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testOptions() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + PORT + "/bookstore/bookurl/http%3A%2F%2Ftest.com%2Frss%2F123");
WebClient.getConfig(wc).getRequestContext().put("org.apache.cxf.http.header.split",true);
Response response=wc.options();
List values=response.getMetadata().get("Allow");
assertNotNull(values);
assertTrue(values.contains("POST") && values.contains("GET") && values.contains("DELETE")&& values.contains("PUT"));
assertEquals(0,((InputStream)response.getEntity()).available());
List date=response.getMetadata().get("Date");
assertNotNull(date);
assertEquals(1,date.size());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSetManyCookiesWebClient() throws Exception {
WebClient client=WebClient.create("http://localhost:" + PORT + "/bookstore/setmanycookies");
Response r=client.type("*/*").get();
assertEquals(200,r.getStatus());
List cookies=r.getMetadata().get("Set-Cookie");
assertNotNull(cookies);
assertEquals(3,cookies.size());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testPostGetBookAdapterList() throws Exception {
JAXBElementProvider> provider=new JAXBElementProvider();
Map outMap=new HashMap();
outMap.put("Books","CollectionWrapper");
outMap.put("books","Book");
provider.setOutTransformElements(outMap);
WebClient wc=WebClient.create("http://localhost:" + PORT + "/bookstore/books/adapter-list",Collections.singletonList(provider));
Collection extends Book> books=wc.type("application/xml").accept("application/xml").postAndGetCollection(new Books(new Book("CXF",123L)),Book.class);
assertEquals(1,books.size());
assertEquals(123L,books.iterator().next().getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookDescriptionHttpResponse() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/httpresponse";
WebClient wc=WebClient.create(address);
WebClient.getConfig(wc).getInInterceptors().add(new LoggingInInterceptor());
Response r=wc.get();
assertEquals("text/plain",r.getMediaType().toString());
assertEquals("Good Book",r.readEntity(String.class));
}
InternalCallVerifier EqualityVerifier
@Test public void testBookWithSpaceProxyNonEncodedSemicolon() throws Exception {
BookStore store=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class);
Book book=store.getBookWithSemicolon("123;","custom;:header");
assertEquals(123L,book.getId());
assertEquals("CXF in Action;",book.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookByHeaderPerRequestInjected() throws Exception {
String address="http://localhost:" + PORT + "/bookstore2/bookheaders/injected";
WebClient wc=WebClient.create(address);
wc.accept("application/xml");
wc.header("BOOK","1","2","3");
Book b=wc.get(Book.class);
assertEquals(123L,b.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookAdapterInfoList() throws Exception {
BookStore store=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class);
List extends BookInfo> list=store.getBookAdapterList();
assertEquals(1,list.size());
BookInfo info=list.get(0);
assertEquals(123L,info.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetHeadBook123WebClient() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/getheadbook/";
WebClient client=WebClient.create(address);
Response r=client.head();
assertEquals("HEAD_HEADER_VALUE",r.getMetadata().getFirst("HEAD_HEADER"));
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetJAXBElementXmlRootBookCollectionWebClient() throws Exception {
WebClient store=WebClient.create("http://localhost:" + PORT + "/bookstore/jaxbelementxmlrootcollections");
Book b1=new Book("CXF in Action",123L);
Book b2=new Book("CXF Rocks",124L);
List books=new ArrayList();
books.add(b1);
books.add(b2);
store.type("application/xml").accept("application/xml");
List books2=new ArrayList(store.postAndGetCollection(books,Book.class,Book.class));
assertNotNull(books2);
assertNotSame(books,books2);
assertEquals(2,books2.size());
Book b11=books2.get(0);
assertEquals(123L,b11.getId());
assertEquals("CXF in Action",b11.getName());
Book b22=books2.get(1);
assertEquals(124L,b22.getId());
assertEquals("CXF Rocks",b22.getName());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetBookResponseAndETag() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/books/response/123";
WebClient wc=WebClient.create(endpointAddress);
Book book=wc.get(Book.class);
assertEquals(200,wc.getResponse().getStatus());
assertEquals(123L,book.getId());
MultivaluedMap headers=wc.getResponse().getMetadata();
assertTrue(headers.size() > 0);
Object etag=headers.getFirst("ETag");
assertNotNull(etag);
assertTrue(etag.toString().startsWith("\""));
assertTrue(etag.toString().endsWith("\""));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookByHeaderPerRequestContextFault() throws Exception {
String address="http://localhost:" + PORT + "/bookstore2/bookheaders";
WebClient wc=WebClient.create(address);
wc.accept("application/xml");
wc.header("BOOK","1","3","4");
Response r=wc.get();
assertEquals(400,r.getStatus());
assertEquals("Context setter: unexpected header value",r.readEntity(String.class));
}
InternalCallVerifier EqualityVerifier
@Test public void testDropJSONRootDynamically(){
WebClient wc=WebClient.create("http://localhost:" + PORT + "/bookstore/dropjsonroot");
wc.accept("application/json");
String response=wc.get(String.class);
assertEquals("{\"id\":123,\"name\":\"CXF in Action\"}",response);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSetCookieWebClient() throws Exception {
WebClient client=WebClient.create("http://localhost:" + PORT + "/bookstore/setcookies");
Response r=client.type("*/*").get();
assertEquals(200,r.getStatus());
List cookies=r.getMetadata().get("Set-Cookie");
assertNotNull(cookies);
assertEquals(1,cookies.size());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetBook123WithProxy() throws Exception {
BookStore bs=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class);
Book b=bs.getBook("123");
assertEquals(b.getId(),123);
}
InternalCallVerifier EqualityVerifier
@Test public void testBookWithSpaceProxyPathUrlEncodedSemicolonOnly() throws Exception {
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
bean.setServiceClass(BookStore.class);
bean.setAddress("http://localhost:" + PORT);
bean.getProperties(true).put("url.encode.client.parameters","true");
bean.getProperties(true).put("url.encode.client.parameters.list",";");
BookStore store=bean.create(BookStore.class);
Book book=store.getBookWithSemicolon("123;:","custom;:header");
assertEquals(123L,book.getId());
assertEquals("CXF in Action%3B:",book.getName());
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testPostGetCollectionGenericEntityAndType() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/collections";
WebClient wc=WebClient.create(endpointAddress);
wc.accept("application/xml").type("application/xml");
Book b1=new Book("CXF in Action",123L);
Book b2=new Book("CXF Rocks",124L);
List books=new ArrayList();
books.add(b1);
books.add(b2);
GenericEntity> genericCollectionEntity=new GenericEntity>(books){
}
;
GenericType> genericResponseType=new GenericType>(){
}
;
List books2=wc.post(genericCollectionEntity,genericResponseType);
assertNotNull(books2);
assertNotSame(books,books2);
assertEquals(2,books2.size());
Book b11=books.get(0);
assertEquals(123L,b11.getId());
assertEquals("CXF in Action",b11.getName());
Book b22=books.get(1);
assertEquals(124L,b22.getId());
assertEquals("CXF Rocks",b22.getName());
assertEquals(200,wc.getResponse().getStatus());
}
InternalCallVerifier EqualityVerifier
@Test public void testBookWithSpaceProxy() throws Exception {
BookStore store=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class);
Book book=store.getBookWithSpace("123");
assertEquals(123L,book.getId());
assertEquals("CXF in Action",book.getName());
}
InternalCallVerifier EqualityVerifier
@Test public void testAddBookNoBody() throws Exception {
PostMethod post=new PostMethod("http://localhost:" + PORT + "/bookstore/books");
post.setRequestHeader("Content-Type","application/xml");
HttpClient httpclient=new HttpClient();
try {
int result=httpclient.executeMethod(post);
assertEquals(400,result);
}
finally {
post.releaseConnection();
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookFromResponseWithWebClient() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/genericresponse/123";
WebClient wc=WebClient.create(address);
Response r=wc.accept("application/xml").get();
assertEquals(200,r.getStatus());
Book book=r.readEntity(Book.class);
assertEquals(123L,book.getId());
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testOptionsOnSubresource() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + PORT + "/bookstore/booksubresource/123");
WebClient.getConfig(wc).getRequestContext().put("org.apache.cxf.http.header.split",true);
Response response=wc.options();
List values=response.getMetadata().get("Allow");
assertNotNull(values);
assertTrue(!values.contains("POST") && values.contains("GET") && !values.contains("DELETE")&& values.contains("PUT"));
assertEquals(0,((InputStream)response.getEntity()).available());
List date=response.getMetadata().get("Date");
assertNotNull(date);
assertEquals(1,date.size());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookRelativeUriAutoRedirect() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/redirect/relative?loop=false";
WebClient wc=WebClient.create(address);
assertEquals(address,wc.getCurrentURI().toString());
WebClient.getConfig(wc).getRequestContext().put("http.redirect.relative.uri","true");
WebClient.getConfig(wc).getHttpConduit().getClient().setAutoRedirect(true);
Response r=wc.get();
Book book=r.readEntity(Book.class);
assertEquals(124L,book.getId());
String newAddress="http://localhost:" + PORT + "/bookstore/redirect/relative?redirect=true";
assertEquals(newAddress,wc.getCurrentURI().toString());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetBookWithCustomHeader() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/books/123";
WebClient wc=WebClient.create(endpointAddress);
Book b=wc.get(Book.class);
assertEquals(123L,b.getId());
MultivaluedMap headers=wc.getResponse().getMetadata();
assertEquals("123",headers.getFirst("BookId"));
assertEquals(MultivaluedMap.class.getName(),headers.getFirst("MAP-NAME"));
assertNotNull(headers.getFirst("Date"));
wc.header("PLAIN-MAP","true");
b=wc.get(Book.class);
assertEquals(123L,b.getId());
headers=wc.getResponse().getMetadata();
assertEquals("321",headers.getFirst("BookId"));
assertEquals(Map.class.getName(),headers.getFirst("MAP-NAME"));
assertNotNull(headers.getFirst("Date"));
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testEmptyPut() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + PORT + "/bookstore/emptyput");
Response response=wc.type("application/json").put(null);
assertEquals(204,response.getStatus());
assertNull(response.getMetadata().getFirst("Content-Type"));
response=wc.put("");
assertEquals(204,response.getStatus());
assertNull(response.getMetadata().getFirst("Content-Type"));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testGetBookQueryGZIP() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/";
WebClient wc=WebClient.create(address);
wc.acceptEncoding("gzip,deflate");
wc.encoding("gzip");
InputStream r=wc.get(InputStream.class);
assertNotNull(r);
GZIPInputStream in=new GZIPInputStream(r);
String s=IOUtils.toString(in);
in.close();
assertTrue(s,s.contains("id>124"));
}
InternalCallVerifier EqualityVerifier
@Test public void testDeleteBookByQuery() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/books/id?value=123";
DeleteMethod post=new DeleteMethod(endpointAddress);
HttpClient httpclient=new HttpClient();
try {
int result=httpclient.executeMethod(post);
assertEquals(200,result);
}
finally {
post.releaseConnection();
}
}
InternalCallVerifier EqualityVerifier
@Test public void testGetBookFromResponseWithProxy() throws Exception {
BookStore bs=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class);
Response r=bs.getGenericResponseBook("123");
assertEquals(200,r.getStatus());
Book book=r.readEntity(Book.class);
assertEquals(123L,book.getId());
}
InternalCallVerifier EqualityVerifier
@Test public void testUpdateBookWithJSON() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/bookswithjson";
File input=new File(getClass().getResource("resources/update_book_json.txt").toURI());
PutMethod put=new PutMethod(endpointAddress);
RequestEntity entity=new FileRequestEntity(input,"application/json; charset=ISO-8859-1");
put.setRequestEntity(entity);
HttpClient httpclient=new HttpClient();
try {
int result=httpclient.executeMethod(put);
assertEquals(200,result);
InputStream expected=getClass().getResourceAsStream("resources/expected_update_book.txt");
assertEquals(stripXmlInstructionIfNeeded(getStringFromInputStream(expected)),stripXmlInstructionIfNeeded(getStringFromInputStream(put.getResponseBodyAsStream())));
}
finally {
put.releaseConnection();
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier IgnoredMethod HybridVerifier
@Test @Ignore public void testProxyUnwrapBookWithXslt() throws Exception {
XSLTJaxbProvider> provider=new XSLTJaxbProvider();
provider.setInTemplate("classpath:/org/apache/cxf/systest/jaxrs/resources/unwrapbook2.xsl");
BookStore bs=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class,Collections.singletonList(provider));
Book book=bs.getWrappedBook2(123L);
assertNotNull(book);
assertEquals(123L,book.getId());
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetJAXBElementBookCollection() throws Exception {
JAXBElementProvider> provider=new JAXBElementProvider();
provider.setMarshallAsJaxbElement(true);
provider.setUnmarshallAsJaxbElement(true);
BookStore store=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class,Collections.singletonList(provider));
BookNoXmlRootElement b1=new BookNoXmlRootElement("CXF in Action",123L);
BookNoXmlRootElement b2=new BookNoXmlRootElement("CXF Rocks",124L);
List> books=new ArrayList>();
books.add(new JAXBElement(new QName("bookNoXmlRootElement"),BookNoXmlRootElement.class,b1));
books.add(new JAXBElement(new QName("bookNoXmlRootElement"),BookNoXmlRootElement.class,b2));
List> books2=store.getJAXBElementBookCollection(books);
assertNotNull(books2);
assertNotSame(books,books2);
assertEquals(2,books2.size());
BookNoXmlRootElement b11=books.get(0).getValue();
assertEquals(123L,b11.getId());
assertEquals("CXF in Action",b11.getName());
BookNoXmlRootElement b22=books.get(1).getValue();
assertEquals(124L,b22.getId());
assertEquals("CXF Rocks",b22.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testPostGetBookAdapterListJSON() throws Exception {
JAXBElementProvider> provider=new JAXBElementProvider();
Map outMap=new HashMap();
outMap.put("Books","CollectionWrapper");
outMap.put("books","Book");
provider.setOutTransformElements(outMap);
WebClient wc=WebClient.create("http://localhost:" + PORT + "/bookstore/books/adapter-list",Collections.singletonList(provider));
Response r=wc.type("application/xml").accept("application/json").post(new Books(new Book("CXF",123L)));
assertEquals("{\"Book\":[{\"id\":123,\"name\":\"CXF\"}]}",IOUtils.readStringFromStream((InputStream)r.getEntity()));
}
InternalCallVerifier EqualityVerifier
@Test public void testBookWithSpaceProxyPathUrlEncoded() throws Exception {
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
bean.setServiceClass(BookStore.class);
bean.setAddress("http://localhost:" + PORT);
bean.setProperties(Collections.singletonMap("url.encode.client.parameters",Boolean.TRUE));
BookStore store=bean.create(BookStore.class);
Book book=store.getBookWithSemicolon("123;:","custom;:header");
assertEquals(123L,book.getId());
assertEquals("CXF in Action%3B%3A",book.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookAdapterInterfaceList() throws Exception {
BookStore store=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class);
List extends BookInfoInterface> list=store.getBookAdapterInterfaceList();
assertEquals(1,list.size());
BookInfoInterface info=list.get(0);
assertEquals(123L,info.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookUntypedStreamingResponse() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/books/streamingresponse";
WebClient wc=WebClient.create(address);
Book book=wc.get(Book.class);
assertEquals(124L,book.getId());
assertEquals("stream",book.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testEchoBookElement() throws Exception {
BookStore store=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class);
JAXBElement element=store.echoBookElement(new JAXBElement(new QName("","Book"),Book.class,new Book("CXF",123L)));
Book book=element.getValue();
assertEquals(123L,book.getId());
assertEquals("CXF",book.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetIntroChapterFromSelectedBook2(){
String address="http://localhost:" + PORT + "/bookstore/";
WebClient wc=WebClient.create(address);
wc.path("books[id=le=123]");
wc.path("chapter");
wc.accept("application/xml");
Chapter chapter=wc.get(Chapter.class);
assertEquals("chapter 1",chapter.getTitle());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testCapturedServerOutFault() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/bookstore/outfault";
WebClient wc=WebClient.create(endpointAddress);
Response r=wc.get();
assertEquals(403,r.getStatus());
}
Class: org.apache.cxf.systest.jaxrs.JAXRSClientServerNonSpringBookTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetPathFromUriInfo() throws Exception {
String address="http://localhost:" + PORT + "/application/bookstore/uifromconstructor";
WebClient wc=WebClient.create(address);
wc.accept("text/plain");
String response=wc.get(String.class);
assertEquals(address + "?prop=cxf",response);
}
InternalCallVerifier EqualityVerifier
@Test public void testGetBook123UserModelAuthorize() throws Exception {
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
bean.setAddress("http://localhost:" + PORT + "/usermodel/bookstore/books");
bean.setUsername("Barry");
bean.setPassword("password");
bean.setModelRef("classpath:org/apache/cxf/systest/jaxrs/resources/resources.xml");
WebClient proxy=bean.createWebClient();
proxy.path("{id}/authorize",123);
Book book=proxy.get(Book.class);
assertEquals(123L,book.getId());
}
InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testGetBooksUserModelInterface() throws Exception {
BookStoreNoAnnotationsInterface proxy=JAXRSClientFactory.createFromModel("http://localhost:" + PORT + "/usermodel2",BookStoreNoAnnotationsInterface.class,"classpath:org/apache/cxf/systest/jaxrs/resources/resources2.xml",null);
Book book=new Book("From Model",1L);
List books=new ArrayList();
books.add(book);
books=proxy.getBooks(books);
assertEquals(1,books.size());
assertNotSame(book,books.get(0));
assertEquals("From Model",books.get(0).getName());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetBook123ApplicationSingleton() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + PORT + "/application/bookstore/default");
wc.accept("application/xml");
Book book=wc.get(Book.class);
assertEquals("default",book.getName());
assertEquals(543L,book.getId());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testGetStaticResource() throws Exception {
String address="http://localhost:" + PORT + "/singleton/staticmodel.xml";
WebClient wc=WebClient.create(address);
String response=wc.get(String.class);
assertTrue(response.startsWith("
InternalCallVerifier EqualityVerifier
@Test public void testUserModelInterfaceOneWay() throws Exception {
BookStoreNoAnnotationsInterface proxy=JAXRSClientFactory.createFromModel("http://localhost:" + PORT + "/usermodel2",BookStoreNoAnnotationsInterface.class,"classpath:org/apache/cxf/systest/jaxrs/resources/resources2.xml",null);
proxy.pingBookStore();
assertEquals(202,WebClient.client(proxy).getResponse().getStatus());
}
Class: org.apache.cxf.systest.jaxrs.JAXRSClientServerODataSearchTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testSearchBook123WithWebClient() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/books/search";
WebClient client=WebClient.create(address);
Book b=client.query("$filter","name eq 'CXF*' and id ge 123 and id lt 124").get(Book.class);
assertEquals(b.getId(),123L);
}
Class: org.apache.cxf.systest.jaxrs.JAXRSClientServerProxySpringBookTest InternalCallVerifier EqualityVerifier
@Test public void testGetBookWithRequestScope(){
WebClient wc=WebClient.create("http://localhost:" + PORT + "/test/request/bookstore/booksecho2");
wc.type("text/plain").accept("text/plain");
wc.header("CustomHeader","custom-header");
String value=wc.post("CXF",String.class);
assertEquals("CXF",value);
assertEquals("custom-header",wc.getResponse().getMetadata().getFirst("CustomHeader"));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetName() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/test/v1/names/1";
WebClient wc=WebClient.create(endpointAddress);
wc.accept("application/json");
String name=wc.get(String.class);
assertEquals("{\"name\":\"Barry\"}",name);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testPutName() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/test/v1/names/1";
WebClient wc=WebClient.create(endpointAddress);
wc.type("application/json").accept("application/json");
String id=wc.put(null,String.class);
assertEquals("1",id);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetWadlResourcesInfo() throws Exception {
WebClient client=WebClient.create("http://localhost:" + PORT + "/test"+ "?_wadl&_type=xml");
WebClient.getConfig(client).getHttpConduit().getClient().setReceiveTimeout(10000000);
Document doc=StaxUtils.read(new InputStreamReader(client.get(InputStream.class),StandardCharsets.UTF_8));
Element root=doc.getDocumentElement();
assertEquals(WadlGenerator.WADL_NS,root.getNamespaceURI());
assertEquals("application",root.getLocalName());
List resourcesEls=DOMUtils.getChildrenWithName(root,WadlGenerator.WADL_NS,"resources");
assertEquals(1,resourcesEls.size());
Element resourcesEl=resourcesEls.get(0);
assertEquals("http://localhost:" + PORT + "/test/",resourcesEl.getAttribute("base"));
List resourceEls=DOMUtils.getChildrenWithName(resourcesEl,WadlGenerator.WADL_NS,"resource");
assertEquals(3,resourceEls.size());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testEchoBook() throws Exception {
URL url=new URL("http://localhost:" + PORT + "/test/5/bookstorestorage/thosebooks");
WebClient wc=WebClient.create(url.toString(),Collections.singletonList(new CustomJaxbElementProvider()));
Response r=wc.post(new Book("proxy",333L));
Book book=r.readEntity(Book.class);
assertEquals(333L,book.getId());
String ct=r.getHeaderString("Content-Type");
assertEquals("application/xml;a=b",ct);
}
Class: org.apache.cxf.systest.jaxrs.JAXRSClientServerResourceCreatedSpringBookTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookSimpleProxy() throws Exception {
String address="http://localhost:" + PORT + "/webapp/rest";
BookStoreSimple bookStore=JAXRSClientFactory.create(address,BookStoreSimple.class);
Book book=bookStore.getBook(444L);
assertEquals(444L,book.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookSimpleBeanParamProxy() throws Exception {
String address="http://localhost:" + PORT + "/webapp/rest";
BookStoreSimple bookStore=JAXRSClientFactory.create(address,BookStoreSimple.class);
Book book=bookStore.getBookBeanParam(new BookStoreSimple.BookBean(444));
assertEquals(444L,book.getId());
}
Class: org.apache.cxf.systest.jaxrs.JAXRSClientServerResourceCreatedSpringProviderTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testPostPetStatusType() throws Exception {
JAXBElementProvider p=new JAXBElementProvider();
p.setUnmarshallAsJaxbElement(true);
WebClient wc=WebClient.create("http://localhost:" + PORT + "/webapp/pets/petstore/jaxb/statusType/",Collections.singletonList(p));
WebClient.getConfig(wc).getInInterceptors().add(new LoggingInInterceptor());
wc.accept("text/xml");
PetStore.PetStoreStatusType type=wc.get(PetStore.PetStoreStatusType.class);
assertEquals(PetStore.CLOSED,type.getStatus());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testBasePetStoreWithoutTrailingSlash() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/webapp/pets";
WebClient client=WebClient.create(endpointAddress);
HTTPConduit conduit=WebClient.getConfig(client).getHttpConduit();
conduit.getClient().setReceiveTimeout(1000000);
conduit.getClient().setConnectionTimeout(1000000);
String value=client.accept("text/plain").get(String.class);
assertEquals(PetStore.CLOSED,value);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testServletConfigInitParam() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/webapp/resources/servlet/config/a";
WebClient wc=WebClient.create(endpointAddress);
wc.accept("text/plain");
assertEquals("avalue",wc.get(String.class));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testBasePetStore() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/webapp/pets/";
WebClient client=WebClient.create(endpointAddress);
HTTPConduit conduit=WebClient.getConfig(client).getHttpConduit();
conduit.getClient().setReceiveTimeout(1000000);
conduit.getClient().setConnectionTimeout(1000000);
String value=client.accept("text/plain").get(String.class);
assertEquals(PetStore.CLOSED,value);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testWadlPublishedEndpointUrl() throws Exception {
String requestURI="http://localhost:" + PORT + "/webapp/resources2";
WebClient client=WebClient.create(requestURI + "?_wadl&_type=xml");
Document doc=StaxUtils.read(new InputStreamReader(client.get(InputStream.class),StandardCharsets.UTF_8));
Element root=doc.getDocumentElement();
assertEquals(WadlGenerator.WADL_NS,root.getNamespaceURI());
assertEquals("application",root.getLocalName());
List resourcesEls=DOMUtils.getChildrenWithName(root,WadlGenerator.WADL_NS,"resources");
assertEquals(1,resourcesEls.size());
Element resourcesEl=resourcesEls.get(0);
assertEquals("http://proxy",resourcesEl.getAttribute("base"));
}
Class: org.apache.cxf.systest.jaxrs.JAXRSClientServerResourceJacksonSpringProviderTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testMultipart() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/webapp/multipart";
MultipartStore proxy=JAXRSClientFactory.create(endpointAddress,MultipartStore.class,Collections.singletonList(new JacksonJsonProvider()));
Book json=new Book("json",1L);
InputStream is1=getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg");
Map attachments=proxy.addBookJsonImageStream(json,is1);
assertEquals(2,attachments.size());
Book json2=((Attachment)attachments.get("application/json")).getObject(Book.class);
assertEquals("json",json2.getName());
assertEquals(1L,json2.getId());
InputStream is2=((Attachment)attachments.get("application/octet-stream")).getObject(InputStream.class);
byte[] image1=IOUtils.readBytesFromStream(getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg"));
byte[] image2=IOUtils.readBytesFromStream(is2);
assertTrue(Arrays.equals(image1,image2));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testEchoSuperBookProxy() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/webapp/store2";
BookStoreSpring proxy=JAXRSClientFactory.create(endpointAddress,BookStoreSpring.class,Collections.singletonList(new JacksonJsonProvider()));
SuperBook book=proxy.echoSuperBookJson(new SuperBook("Super",124L,true));
assertEquals(124L,book.getId());
assertTrue(book.isSuperBook());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetSuperBookProxy() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/webapp/store2";
BookStoreSpring proxy=JAXRSClientFactory.create(endpointAddress,BookStoreSpring.class,Collections.singletonList(new JacksonJsonProvider()));
SuperBook book=proxy.getSuperBookJson();
assertEquals(999L,book.getId());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testEchoGenericSuperBookCollectionProxy() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/webapp/custombus/genericstore";
GenericBookStoreSpring proxy=JAXRSClientFactory.create(endpointAddress,GenericBookStoreSpring.class,Collections.singletonList(new JacksonJsonProvider()));
List books=proxy.echoSuperBookCollectionJson(Collections.singletonList(new SuperBook("Super",124L,true)));
assertEquals(124L,books.get(0).getId());
assertTrue(books.get(0).isSuperBook());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testEchoGenericSuperBookProxy2JsonType() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/webapp/genericstore2type";
GenericBookStoreSpring2 proxy=JAXRSClientFactory.create(endpointAddress,GenericBookStoreSpring2.class,Collections.singletonList(new JacksonJsonProvider()));
WebClient.getConfig(proxy).getHttpConduit().getClient().setReceiveTimeout(1000000000L);
WebClient.client(proxy).type("application/json").accept("application/json");
SuperBook2 book=proxy.echoSuperBookType(new SuperBook2("Super",124L,true));
assertEquals(124L,book.getId());
assertTrue(book.isSuperBook());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetSuperBookCollectionProxy() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/webapp/store2";
BookStoreSpring proxy=JAXRSClientFactory.create(endpointAddress,BookStoreSpring.class,Collections.singletonList(new JacksonJsonProvider()));
List books=proxy.getSuperBookCollectionJson();
assertEquals(999L,books.get(0).getId());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testEchoGenericSuperBookCollectionProxy2XmlType() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/webapp/genericstore2type";
JAXBElementProvider jaxbProvider=new JAXBElementProvider();
jaxbProvider.setMarshallAsJaxbElement(true);
jaxbProvider.setUnmarshallAsJaxbElement(true);
GenericBookStoreSpring2 proxy=JAXRSClientFactory.create(endpointAddress,GenericBookStoreSpring2.class,Collections.singletonList(jaxbProvider));
WebClient.client(proxy).type("application/xml").accept("application/xml");
WebClient.getConfig(proxy).getHttpConduit().getClient().setReceiveTimeout(1000000000L);
List books=proxy.echoSuperBookTypeCollection(Collections.singletonList(new SuperBook2("Super",124L,true)));
assertEquals(124L,books.get(0).getId());
assertTrue(books.get(0).isSuperBook());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testEchoGenericSuperBookProxy2Xml() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/webapp/genericstore2";
JAXBElementProvider jaxbProvider=new JAXBElementProvider();
jaxbProvider.setXmlRootAsJaxbElement(true);
jaxbProvider.setMarshallAsJaxbElement(true);
GenericBookStoreSpring2 proxy=JAXRSClientFactory.create(endpointAddress,GenericBookStoreSpring2.class,Collections.singletonList(jaxbProvider));
WebClient.getConfig(proxy).getHttpConduit().getClient().setReceiveTimeout(1000000000L);
WebClient.client(proxy).type("application/xml").accept("application/xml");
SuperBook book=proxy.echoSuperBook(new SuperBook("Super",124L,true));
assertEquals(124L,book.getId());
assertTrue(book.isSuperBook());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testEchoGenericSuperBookCollectionWebClient() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/webapp/custombus/genericstore/books/superbooks";
WebClient wc=WebClient.create(endpointAddress,Collections.singletonList(new JacksonJsonProvider()));
WebClient.getConfig(wc).getHttpConduit().getClient().setReceiveTimeout(100000000L);
wc.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON);
Collection extends SuperBook> books=wc.postAndGetCollection(Collections.singletonList(new SuperBook("Super",124L,true)),SuperBook.class,SuperBook.class);
SuperBook book=books.iterator().next();
assertEquals(124L,book.getId());
assertTrue(book.isSuperBook());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testGetGenericSuperBookCollectionWebClient() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/webapp/custombus/genericstore/books/superbooks2";
WebClient wc=WebClient.create(endpointAddress,Collections.singletonList(new JacksonJsonProvider()));
WebClient.getConfig(wc).getHttpConduit().getClient().setReceiveTimeout(100000000L);
wc.accept(MediaType.APPLICATION_JSON);
List books=wc.get(new GenericType>(){
}
);
SuperBook book=books.iterator().next();
assertEquals(124L,book.getId());
assertTrue(book.isSuperBook());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testEchoGenericSuperBookProxy() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/webapp/custombus/genericstore";
GenericBookStoreSpring proxy=JAXRSClientFactory.create(endpointAddress,GenericBookStoreSpring.class,Collections.singletonList(new JacksonJsonProvider()));
WebClient.getConfig(proxy).getHttpConduit().getClient().setReceiveTimeout(1000000000L);
SuperBook book=proxy.echoSuperBookJson(new SuperBook("Super",124L,true));
assertEquals(124L,book.getId());
assertTrue(book.isSuperBook());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testEchoGenericSuperBookProxy2Json() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/webapp/genericstore2";
GenericBookStoreSpring2 proxy=JAXRSClientFactory.create(endpointAddress,GenericBookStoreSpring2.class,Collections.singletonList(new JacksonJsonProvider()));
WebClient.getConfig(proxy).getHttpConduit().getClient().setReceiveTimeout(1000000000L);
WebClient.client(proxy).type("application/json").accept("application/json");
SuperBook book=proxy.echoSuperBook(new SuperBook("Super",124L,true));
assertEquals(124L,book.getId());
assertTrue(book.isSuperBook());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testEchoGenericSuperBookCollectionProxy2Json() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/webapp/genericstore2";
GenericBookStoreSpring2 proxy=JAXRSClientFactory.create(endpointAddress,GenericBookStoreSpring2.class,Collections.singletonList(new JacksonJsonProvider()));
WebClient.client(proxy).type("application/json").accept("application/json");
List books=proxy.echoSuperBookCollection(Collections.singletonList(new SuperBook("Super",124L,true)));
assertEquals(124L,books.get(0).getId());
assertTrue(books.get(0).isSuperBook());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testEchoGenericSuperBookProxy2XmlType() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/webapp/genericstore2type";
JAXBElementProvider jaxbProvider=new JAXBElementProvider();
jaxbProvider.setMarshallAsJaxbElement(true);
jaxbProvider.setUnmarshallAsJaxbElement(true);
GenericBookStoreSpring2 proxy=JAXRSClientFactory.create(endpointAddress,GenericBookStoreSpring2.class,Collections.singletonList(jaxbProvider));
WebClient.getConfig(proxy).getHttpConduit().getClient().setReceiveTimeout(1000000000L);
WebClient.client(proxy).type("application/xml").accept("application/xml");
SuperBook2 book=proxy.echoSuperBookType(new SuperBook2("Super",124L,true));
assertEquals(124L,book.getId());
assertTrue(book.isSuperBook());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testEchoGenericSuperBookWebClientXml() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/webapp/custombus/genericstore/books/superbook";
WebClient wc=WebClient.create(endpointAddress);
wc.accept(MediaType.APPLICATION_XML).type(MediaType.APPLICATION_XML);
SuperBook book=wc.post(new SuperBook("Super",124L,true),SuperBook.class);
assertEquals(124L,book.getId());
assertTrue(book.isSuperBook());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testEchoGenericSuperBookCollectionWebClientXml() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/webapp/custombus/genericstore/books/superbooks";
WebClient wc=WebClient.create(endpointAddress);
wc.accept(MediaType.APPLICATION_XML).type(MediaType.APPLICATION_XML);
Collection extends SuperBook> books=wc.postAndGetCollection(Collections.singletonList(new SuperBook("Super",124L,true)),SuperBook.class,SuperBook.class);
SuperBook book=books.iterator().next();
assertEquals(124L,book.getId());
assertTrue(book.isSuperBook());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testEchoGenericSuperBookWebClient() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/webapp/custombus/genericstore/books/superbook";
WebClient wc=WebClient.create(endpointAddress,Collections.singletonList(new JacksonJsonProvider()));
wc.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON);
SuperBook book=wc.post(new SuperBook("Super",124L,true),SuperBook.class);
assertEquals(124L,book.getId());
assertTrue(book.isSuperBook());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testEchoGenericSuperBookCollectionProxy2Xml() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/webapp/genericstore2";
JAXBElementProvider jaxbProvider=new JAXBElementProvider();
jaxbProvider.setMarshallAsJaxbElement(true);
jaxbProvider.setUnmarshallAsJaxbElement(true);
GenericBookStoreSpring2 proxy=JAXRSClientFactory.create(endpointAddress,GenericBookStoreSpring2.class,Collections.singletonList(jaxbProvider));
WebClient.client(proxy).type("application/xml").accept("application/xml");
WebClient.getConfig(proxy).getHttpConduit().getClient().setReceiveTimeout(1000000000L);
List books=proxy.echoSuperBookCollection(Collections.singletonList(new SuperBook("Super",124L,true)));
assertEquals(124L,books.get(0).getId());
assertTrue(books.get(0).isSuperBook());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetCollectionOfBooks() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/webapp/store1/bookstore/collections";
WebClient wc=WebClient.create(endpointAddress,Collections.singletonList(new JacksonJsonProvider()));
wc.accept("application/json");
Collection extends Book> collection=wc.getCollection(Book.class);
assertEquals(1,collection.size());
Book book=collection.iterator().next();
assertEquals(123L,book.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetCollectionOfSuperBooks() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/webapp/store2/books/superbooks";
WebClient wc=WebClient.create(endpointAddress,Collections.singletonList(new JacksonJsonProvider()));
wc.accept("application/json");
Collection extends Book> collection=wc.getCollection(Book.class);
assertEquals(1,collection.size());
Book book=collection.iterator().next();
assertEquals(999L,book.getId());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testEchoSuperBookCollectionProxy() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/webapp/store2";
BookStoreSpring proxy=JAXRSClientFactory.create(endpointAddress,BookStoreSpring.class,Collections.singletonList(new JacksonJsonProvider()));
WebClient.getConfig(proxy).getHttpConduit().getClient().setReceiveTimeout(10000000L);
List books=proxy.echoSuperBookCollectionJson(Collections.singletonList(new SuperBook("Super",124L,true)));
assertEquals(124L,books.get(0).getId());
assertTrue(books.get(0).isSuperBook());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetGenericSuperBookInt1() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/webapp/genericstoreInt1/int/books/superbook";
WebClient wc=WebClient.create(endpointAddress,Collections.singletonList(new JacksonJsonProvider()));
WebClient.getConfig(wc).getHttpConduit().getClient().setReceiveTimeout(1000000000L);
GenericType> genericResponseType=new GenericType>(){
}
;
List books=wc.get(genericResponseType);
assertEquals(1,books.size());
assertEquals(111L,books.get(0).getId());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testEchoGenericSuperBookCollectionProxy2JsonType() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/webapp/genericstore2type";
GenericBookStoreSpring2 proxy=JAXRSClientFactory.create(endpointAddress,GenericBookStoreSpring2.class,Collections.singletonList(new JacksonJsonProvider()));
WebClient.client(proxy).type("application/json").accept("application/json");
List books=proxy.echoSuperBookTypeCollection(Collections.singletonList(new SuperBook2("Super",124L,true)));
assertEquals(124L,books.get(0).getId());
assertTrue(books.get(0).isSuperBook());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetGenericSuperBookInt2() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/webapp/genericstoreInt2";
GenericBookServiceInterface proxy=JAXRSClientFactory.create(endpointAddress,GenericBookServiceInterface.class,Collections.singletonList(new JacksonJsonProvider()));
WebClient.getConfig(proxy).getHttpConduit().getClient().setReceiveTimeout(1000000000L);
List books=proxy.getSuperBook();
assertEquals(1,books.size());
assertEquals(111L,books.get(0).getId());
}
Class: org.apache.cxf.systest.jaxrs.JAXRSClientServerSpringBookTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookWithEncodedSemicolonAndMatrixParam() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/the/thebooks/bookstore/semicolon2%3B;a=b";
WebClient client=WebClient.create(endpointAddress);
WebClient.getConfig(client).getHttpConduit().getClient().setReceiveTimeout(1000000);
Book book=client.get(Book.class);
assertEquals(333L,book.getId());
assertEquals(";b",book.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testPostBookXsiTypeProxy() throws Exception {
String address="http://localhost:" + PORT + "/the/thebooksxsi/bookstore";
JAXBElementProvider provider=new JAXBElementProvider();
provider.setExtraClass(new Class[]{SuperBook.class});
provider.setJaxbElementClassNames(Collections.singletonList(Book.class.getName()));
BookStoreSpring bookStore=JAXRSClientFactory.create(address,BookStoreSpring.class,Collections.singletonList(provider));
SuperBook book=new SuperBook("SuperBook2",999L,true);
Book book2=bookStore.postGetBookXsiType(book);
assertEquals("SuperBook2",book2.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testEchoBookForm() throws Exception {
String address="http://localhost:" + PORT + "/bus/thebooksform/bookform";
WebClient wc=WebClient.create(address);
Book b=wc.form(new Form().param("name","CXFForm").param("id","125")).readEntity(Book.class);
assertEquals("CXFForm",b.getName());
assertEquals(125L,b.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testPostBookXsiType() throws Exception {
String address="http://localhost:" + PORT + "/the/thebooksxsi/bookstore/books/xsitype";
JAXBElementProvider provider=new JAXBElementProvider();
provider.setExtraClass(new Class[]{SuperBook.class});
provider.setJaxbElementClassNames(Collections.singletonList(Book.class.getName()));
WebClient wc=WebClient.create(address,Collections.singletonList(provider));
wc.accept("application/xml");
wc.type("application/xml");
SuperBook book=new SuperBook("SuperBook2",999L,true);
Book book2=wc.invoke("POST",book,Book.class,Book.class);
assertEquals("SuperBook2",book2.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookWithoutJsonpCallback() throws Exception {
String url="http://localhost:" + PORT + "/the/jsonp/books/123";
WebClient client=WebClient.create(url);
client.accept("application/json, application/x-javascript");
WebClient.getConfig(client).getHttpConduit().getClient().setReceiveTimeout(1000000L);
Response r=client.get();
assertEquals("application/json",r.getMetadata().getFirst("Content-Type"));
assertEquals("{\"Book\":{\"id\":123,\"name\":\"CXF in Action\"}}",IOUtils.readStringFromStream((InputStream)r.getEntity()));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testBookDepthExceededXMLSourceStax() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/the/thebooks9stax/depth-source";
WebClient wc=WebClient.create(endpointAddress);
Response r=wc.post(new Book("CXF",123L));
assertEquals(413,r.getStatus());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testBookDepthExceededJettison() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/the/thebooks10/depth";
WebClient wc=WebClient.create(endpointAddress);
wc.accept("application/json").type("application/json");
Response r=wc.post(new Book("CXF",123L));
assertEquals(413,r.getStatus());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testBookDepthExceededXMLDomStax() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/the/thebooks9stax/depth-dom";
WebClient wc=WebClient.create(endpointAddress);
Response r=wc.post(new Book("CXF",123L));
assertEquals(413,r.getStatus());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testTooManyFormParams() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/the/thebooks9/depth-form";
WebClient wc=WebClient.create(endpointAddress);
Response r=wc.form(new Form().param("a","b"));
assertEquals(204,r.getStatus());
r=wc.form(new Form().param("a","b").param("c","b"));
assertEquals(413,r.getStatus());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testPostGeneratedBook() throws Exception {
String baseAddress="http://localhost:" + PORT + "/the/generated";
JAXBElementProvider> provider=new JAXBElementProvider();
provider.setJaxbElementClassMap(Collections.singletonMap("org.apache.cxf.systest.jaxrs.codegen.schema.Book","{http://superbooks}thebook"));
org.apache.cxf.systest.jaxrs.codegen.service.BookStore bookStore=JAXRSClientFactory.create(baseAddress,org.apache.cxf.systest.jaxrs.codegen.service.BookStore.class,Collections.singletonList(provider));
org.apache.cxf.systest.jaxrs.codegen.schema.Book book=new org.apache.cxf.systest.jaxrs.codegen.schema.Book();
book.setId(123);
bookStore.addBook(123,book);
Response r=WebClient.client(bookStore).getResponse();
assertEquals(204,r.getStatus());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testBookDepthExceededXMLSource() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/the/thebooks9/depth-source";
WebClient wc=WebClient.create(endpointAddress);
WebClient.getConfig(wc).getHttpConduit().getClient().setReceiveTimeout(1000000L);
Response r=wc.post(new Book("CXF",123L));
assertEquals(413,r.getStatus());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testEchoBookFormXml() throws Exception {
String address="http://localhost:" + PORT + "/bus/thebooksform/bookform";
WebClient wc=WebClient.create(address);
WebClient.getConfig(wc).getHttpConduit().getClient().setReceiveTimeout(10000000L);
Book b=wc.type("application/xml").post(new Book("CXFFormXml",125L)).readEntity(Book.class);
assertEquals("CXFFormXml",b.getName());
assertEquals(125L,b.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookJsonp() throws Exception {
String url="http://localhost:" + PORT + "/the/jsonp/books/123";
WebClient client=WebClient.create(url);
client.accept("application/json, application/x-javascript");
client.query("_jsonp","callback");
Response r=client.get();
assertEquals("application/x-javascript",r.getMetadata().getFirst("Content-Type"));
assertEquals("callback({\"Book\":{\"id\":123,\"name\":\"CXF in Action\"}});",IOUtils.readStringFromStream((InputStream)r.getEntity()));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetDefaultBookMatrixParam() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/the/bookstore/2/";
WebClient wc=WebClient.create(endpointAddress);
wc.matrix("a","b");
wc.accept("application/json");
WebClient.getConfig(wc).getHttpConduit().getClient().setReceiveTimeout(1000000L);
Book book=wc.get(Book.class);
assertEquals(123L,book.getId());
assertEquals("Defaultb",book.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookLink() throws Exception {
String address="http://localhost:" + PORT + "/the/bookstore/link";
WebClient wc=WebClient.create(address);
Response r=wc.get();
Link l=r.getLink("self");
assertEquals(" ;rel=\"self\"",l.toString());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookXsiType() throws Exception {
String address="http://localhost:" + PORT + "/the/thebooksxsi/bookstore/books/xsitype";
WebClient wc=WebClient.create(address);
WebClient.getConfig(wc).getHttpConduit().getClient().setReceiveTimeout(10000000);
wc.accept("application/xml");
Book book=wc.get(Book.class);
assertEquals("SuperBook",book.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookXSLTHtml() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/the/thebooks5/bookstore/books/xslt";
WebClient wc=WebClient.create(endpointAddress);
wc.accept("application/xhtml+xml").path(666).matrix("name2",2).query("name","Action - ");
XMLSource source=wc.get(XMLSource.class);
source.setBuffering();
Map namespaces=new HashMap();
namespaces.put("xhtml","http://www.w3.org/1999/xhtml");
Book2 b=source.getNode("xhtml:html/xhtml:body/xhtml:ul/xhtml:Book",namespaces,Book2.class);
assertEquals(666,b.getId());
assertEquals("CXF in Action - 2",b.getName());
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testAddInvalidBookDuplicateElementJson() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + PORT + "/the/bookstore/books/convert");
wc.type("application/json");
InputStream is=getClass().getResourceAsStream("resources/add_book2json_duplicate.txt");
assertNotNull(is);
Response r=wc.post(is);
assertEquals(400,r.getStatus());
String content=IOUtils.readStringFromStream((InputStream)r.getEntity());
assertTrue(content,content.contains("Invalid content was found starting with element"));
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testReaderWriterFromJaxrsFilters() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/the/thebooksWithStax/bookstore/books/convert2/123";
WebClient wc=WebClient.create(endpointAddress);
wc.type("application/xml").accept("application/xml");
Book2 b=new Book2();
b.setId(777L);
b.setName("CXF - 777");
Book2 b2=wc.invoke("PUT",b,Book2.class);
assertNotSame(b,b2);
assertEquals(777,b2.getId());
assertEquals("CXF - 777",b2.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookById() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/the/bookstore/2/123";
WebClient wc=WebClient.create(endpointAddress);
wc.accept("application/json");
Book book=wc.get(Book.class);
assertEquals(123L,book.getId());
assertEquals("Id",book.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetBookUserResourceFromProxy() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/the/thebooks6";
BookStoreNoAnnotations bStore=JAXRSClientFactory.createFromModel(endpointAddress,BookStoreNoAnnotations.class,"classpath:/org/apache/cxf/systest/jaxrs/resources/resources.xml",null);
Book b=bStore.getBook(123L);
assertNotNull(b);
assertEquals(123L,b.getId());
assertEquals("CXF in Action",b.getName());
ChapterNoAnnotations proxy=bStore.getBookChapter(123L);
ChapterNoAnnotations c=proxy.getItself();
assertNotNull(c);
assertEquals(1,c.getId());
assertEquals("chapter 1",c.getTitle());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testBookDepthExceededXML() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/the/thebooks9/depth";
WebClient wc=WebClient.create(endpointAddress);
Response r=wc.post(new Book("CXF",123L));
assertEquals(413,r.getStatus());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testBookDepthExceededXMLStax() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/the/thebooks9stax/depth";
WebClient wc=WebClient.create(endpointAddress);
Response r=wc.post(new Book("CXF",123L));
assertEquals(413,r.getStatus());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetGenericBook() throws Exception {
String baseAddress="http://localhost:" + PORT + "/the/thebooks8/books";
WebClient wc=WebClient.create(baseAddress);
WebClient.getConfig(wc).getHttpConduit().getClient().setReceiveTimeout(10000000);
Long id=wc.type("application/xml").accept("text/plain").post(new Book("CXF",1L),Long.class);
assertEquals(new Long(1),id);
Book book=wc.replaceHeader("Accept","application/xml").query("id",1L).get(Book.class);
assertEquals("CXF",book.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookXSLTXml() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/the/thebooks5/bookstore/books/xslt";
WebClient wc=WebClient.create(endpointAddress);
wc.accept("application/xml").path(666).matrix("name2",2).query("name","Action - ");
Book b=wc.get(Book.class);
assertEquals(666,b.getId());
assertEquals("CXF in Action - 2",b.getName());
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testReaderWriterFromInterceptors() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/the/thebooksWithStax/bookstore/books/convert";
WebClient wc=WebClient.create(endpointAddress);
wc.type("application/xml").accept("application/xml");
Book2 b=new Book2();
b.setId(777L);
b.setName("CXF - 777");
Book2 b2=wc.invoke("POST",b,Book2.class);
assertNotSame(b,b2);
assertEquals(777,b2.getId());
assertEquals("CXF - 777",b2.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetDefaultBook() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/the/bookstore";
WebClient wc=WebClient.create(endpointAddress);
wc.accept("application/json");
Book book=wc.get(Book.class);
assertEquals(123L,book.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookWithEncodedSemicolon() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/the/thebooks/bookstore/semicolon%3B";
WebClient client=WebClient.create(endpointAddress);
Book book=client.get(Book.class);
assertEquals(333L,book.getId());
assertEquals(";",book.getName());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetWadlFromWadlLocation() throws Exception {
String address="http://localhost:" + PORT + "/the/generated";
WebClient client=WebClient.create(address + "/bookstore" + "?_wadl&_type=xml");
Document doc=StaxUtils.read(new InputStreamReader(client.get(InputStream.class),StandardCharsets.UTF_8));
List resources=checkWadlResourcesInfo(doc,address,"/schemas/book.xsd",2);
assertEquals("",resources.get(0).getAttribute("type"));
String type=resources.get(1).getAttribute("type");
String resourceTypeAddress=address + "/bookstoreImportResourceType.wadl#bookstoreType";
assertEquals(resourceTypeAddress,type);
checkSchemas(address,"/schemas/book.xsd","/schemas/chapter.xsd","include");
checkSchemas(address,"/schemas/chapter.xsd",null,null);
checkWadlResourcesType(address,resourceTypeAddress,"/schemas/book.xsd");
String templateRef=null;
NodeList nd=doc.getChildNodes();
for (int i=0; i < nd.getLength(); i++) {
Node n=nd.item(i);
if (n.getNodeType() == Document.PROCESSING_INSTRUCTION_NODE) {
String piData=((ProcessingInstruction)n).getData();
int hRefStart=piData.indexOf("href=\"");
if (hRefStart > 0) {
int hRefEnd=piData.indexOf("\"",hRefStart + 6);
templateRef=piData.substring(hRefStart + 6,hRefEnd);
}
}
}
assertNotNull(templateRef);
WebClient client2=WebClient.create(templateRef);
WebClient.getConfig(client2).getHttpConduit().getClient().setReceiveTimeout(1000000L);
String template=client2.get(String.class);
assertNotNull(template);
assertTrue(template.indexOf("
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testBookDepthExceededXMLDom() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/the/thebooks9/depth-dom";
WebClient wc=WebClient.create(endpointAddress);
Response r=wc.post(new Book("CXF",123L));
assertEquals(413,r.getStatus());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testGetBookJsonpJackson() throws Exception {
String url="http://localhost:" + PORT + "/bus/jsonp2/books/123";
WebClient client=WebClient.create(url);
WebClient.getConfig(client).getHttpConduit().getClient().setReceiveTimeout(10000000);
client.accept("application/json, application/x-javascript");
client.query("_jsonp","callback");
Response r=client.get();
assertEquals("application/x-javascript",r.getMetadata().getFirst("Content-Type"));
String response=IOUtils.readStringFromStream((InputStream)r.getEntity());
assertTrue(response.startsWith("callback({\"class\":\"org.apache.cxf.systest.jaxrs.Book\","));
assertTrue(response.endsWith("});"));
assertTrue(response.contains("\"id\":123"));
assertTrue(response.contains("\"name\":\"CXF in Action\""));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetDefaultBook2() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/the/bookstore/2/";
WebClient wc=WebClient.create(endpointAddress);
wc.accept("application/json");
Book book=wc.get(Book.class);
assertEquals(123L,book.getId());
assertEquals("Default",book.getName());
}
Class: org.apache.cxf.systest.jaxrs.JAXRSClientServerStreamingTest InternalCallVerifier EqualityVerifier
@Test public void testGetBook123Fail() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + PORT + "/bookstore/books/text/xml/123");
wc.accept("text/xml");
wc.header("fail-write","yes");
Response r=wc.get();
assertEquals(500,r.getStatus());
}
Class: org.apache.cxf.systest.jaxrs.JAXRSClientServerThrottledTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookOK() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/books/query/default";
WebClient wc=WebClient.create(address,"alice","password",null);
Response r=wc.get();
assertEquals(200,r.getStatus());
assertEquals(123L,r.readEntity(Book.class).getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookRetryAfter() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/books/query/default";
WebClient wc=WebClient.create(address);
Response r=wc.get();
assertEquals(503,r.getStatus());
assertEquals("2",r.getHeaderString("Retry-After"));
}
Class: org.apache.cxf.systest.jaxrs.JAXRSClientServerUserResourceDefaultTest InternalCallVerifier EqualityVerifier
@Test public void testEchoBookDefault() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + PORT + "/default/echobookdefault");
Book b=wc.type("application/xml").accept("application/xml").post(new Book("echo",444L),Book.class);
assertEquals("echo",b.getName());
assertEquals(444L,b.getId());
}
InternalCallVerifier EqualityVerifier
@Test public void testEchoBook() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + PORT + "/default/echobook");
Book b=wc.type("application/xml").accept("application/xml").post(new Book("echo",333L),Book.class);
assertEquals("echo",b.getName());
assertEquals(333L,b.getId());
}
Class: org.apache.cxf.systest.jaxrs.JAXRSContinuationsServlet3Test InternalCallVerifier EqualityVerifier
@Test public void testGetBookUnmappedFromFilter() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + getPort() + getBaseAddress()+ "/books/unmappedFromFilter");
wc.accept("text/plain");
Response r=wc.get();
assertEquals(500,r.getStatus());
}
Class: org.apache.cxf.systest.jaxrs.JAXRSDataBindingTest InternalCallVerifier EqualityVerifier
@Test public void testGetBookAegis() throws Exception {
WebClient client=WebClient.create("http://localhost:" + PORT + "/databinding/aegis/bookstore/books/123",Collections.singletonList(new AegisElementProvider()));
Book book=client.accept("application/xml").get(Book.class);
assertEquals(123L,book.getId());
assertEquals("CXF in Action",book.getName());
}
InternalCallVerifier EqualityVerifier
@Test public void testSDOStructureJSON() throws Exception {
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
DataBinding db=new SDODataBinding();
bean.setDataBinding(db);
DataBindingJSONProvider provider=new DataBindingJSONProvider();
provider.setNamespaceMap(Collections.singletonMap("http://apache.org/structure/types","p0"));
provider.setDataBinding(db);
bean.setProvider(provider);
bean.setAddress("http://localhost:" + PORT + "/databinding/sdo");
bean.setResourceClass(SDOResource.class);
List> list=new ArrayList>();
list.add(new LoggingInInterceptor());
bean.setInInterceptors(list);
SDOResource client=bean.create(SDOResource.class);
WebClient.client(client).accept("application/json");
Structure struct=client.getStructure();
assertEquals("sdo",struct.getText());
assertEquals(123.5,struct.getDbl(),0.01);
assertEquals(3,struct.getInt());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetBookJIBX() throws Exception {
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
bean.setDataBinding(new JibxDataBinding());
bean.setAddress("http://localhost:" + PORT + "/databinding/jibx");
bean.setResourceClass(JibxResource.class);
JibxResource client=bean.create(JibxResource.class);
org.apache.cxf.systest.jaxrs.codegen.jibx.Book b=client.getBook();
assertEquals("JIBX",b.getName());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetBookJAXB() throws Exception {
WebClient client=WebClient.create("http://localhost:" + PORT + "/databinding/jaxb/bookstore/books/123");
Book book=client.accept("application/xml").get(Book.class);
assertEquals(123L,book.getId());
assertEquals("CXF in Action",book.getName());
}
Class: org.apache.cxf.systest.jaxrs.JAXRSLocalTransportTest InternalCallVerifier EqualityVerifier
@Test public void testWebClientDirectDispatchBookType() throws Exception {
WebClient localClient=WebClient.create("local://books",Collections.singletonList(new JacksonJsonProvider()));
WebClient.getConfig(localClient).getRequestContext().put(LocalConduit.DIRECT_DISPATCH,Boolean.TRUE);
localClient.path("bookstore/booktype");
BookType book=localClient.get(BookType.class);
assertEquals(124L,book.getId());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testProxyEmptyResponseDirectDispatch() throws Exception {
BookStore localProxy=JAXRSClientFactory.create("local://books",BookStore.class);
WebClient.getConfig(localProxy).getRequestContext().put(LocalConduit.DIRECT_DISPATCH,"true");
assertNull(localProxy.getEmptyBook());
assertEquals(204,WebClient.client(localProxy).getResponse().getStatus());
}
InternalCallVerifier EqualityVerifier
@Test public void testProxyPipedDispatchGet() throws Exception {
BookStore localProxy=JAXRSClientFactory.create("local://books",BookStore.class);
Book book=localProxy.getBook("123");
assertEquals(123L,book.getId());
}
InternalCallVerifier EqualityVerifier
@Test public void testProxyPipedDispatchGetBookType() throws Exception {
BookStore localProxy=JAXRSClientFactory.create("local://books",BookStore.class,Collections.singletonList(new JacksonJsonProvider()));
BookType book=localProxy.getBookType();
assertEquals(124L,book.getId());
}
InternalCallVerifier EqualityVerifier
@Test public void testSubresourceProxyDirectDispatchGet() throws Exception {
BookStore localProxy=JAXRSClientFactory.create("local://books",BookStore.class);
WebClient.getConfig(localProxy).getRequestContext().put(LocalConduit.DIRECT_DISPATCH,"true");
Book bookSubProxy=localProxy.getBookSubResource("123");
Book book=bookSubProxy.retrieveState();
assertEquals(123L,book.getId());
}
InternalCallVerifier EqualityVerifier
@Test public void testProxyServerOutFault() throws Exception {
BookStore localProxy=JAXRSClientFactory.create("local://books",BookStore.class);
Response r=localProxy.outfault();
assertEquals(403,r.getStatus());
}
InternalCallVerifier EqualityVerifier
@Test public void testProxyServerInFaultMapped() throws Exception {
BookStore localProxy=JAXRSClientFactory.create("local://books",BookStore.class);
Response r=localProxy.infault();
assertEquals(401,r.getStatus());
}
InternalCallVerifier EqualityVerifier
@Test public void testProxyWithQuery() throws Exception {
BookStore localProxy=JAXRSClientFactory.create("local://books",BookStore.class);
WebClient.getConfig(localProxy).getRequestContext().put(LocalConduit.DIRECT_DISPATCH,Boolean.TRUE);
Book book=localProxy.getBookByURLQuery(new String[]{"1","2","3"});
assertEquals(123L,book.getId());
}
InternalCallVerifier EqualityVerifier
@Test public void testProxyServerOutFaultDirectDispacth() throws Exception {
BookStore localProxy=JAXRSClientFactory.create("local://books",BookStore.class);
WebClient.getConfig(localProxy).getRequestContext().put(LocalConduit.DIRECT_DISPATCH,"true");
Response r=localProxy.outfault();
assertEquals(403,r.getStatus());
}
InternalCallVerifier EqualityVerifier
@Test public void testWebClientPipedDispatch() throws Exception {
WebClient localClient=WebClient.create("local://books");
localClient.accept("text/xml");
localClient.path("bookstore/books");
Book book=localClient.post(new Book("New",124L),Book.class);
assertEquals(124L,book.getId());
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testProxyDirectDispatchPostWithGzip() throws Exception {
BookStore localProxy=JAXRSClientFactory.create("local://books",BookStore.class);
WebClient.getConfig(localProxy).getRequestContext().put(LocalConduit.DIRECT_DISPATCH,Boolean.TRUE);
Response response=localProxy.addBook(new Book("New",124L));
assertEquals(200,response.getStatus());
assertTrue(response.getMetadata().getFirst("Location") instanceof URI);
}
InternalCallVerifier EqualityVerifier
@Test public void testProxyPipedDispatchPost() throws Exception {
BookStoreSpring localProxy=JAXRSClientFactory.create("local://books",BookStoreSpring.class);
Book response=localProxy.convertBook(new Book2("New",124L));
assertEquals(124L,response.getId());
}
InternalCallVerifier EqualityVerifier
@Test public void testProxyServerInFaultEscaped() throws Exception {
BookStore localProxy=JAXRSClientFactory.create("local://books",BookStore.class);
Response r=localProxy.infault2();
assertEquals(500,r.getStatus());
}
InternalCallVerifier EqualityVerifier
@Test public void testProxyServerInFaultDirectDispatch() throws Exception {
BookStore localProxy=JAXRSClientFactory.create("local://books",BookStore.class);
WebClient.getConfig(localProxy).getRequestContext().put(LocalConduit.DIRECT_DISPATCH,"true");
WebClient.getConfig(localProxy).getInFaultInterceptors().add(new TestFaultInInterceptor());
Response r=localProxy.infault2();
assertEquals(500,r.getStatus());
}
InternalCallVerifier EqualityVerifier
@Test public void testWebClientDirectDispatch() throws Exception {
WebClient localClient=WebClient.create("local://books");
WebClient.getConfig(localClient).getRequestContext().put(LocalConduit.DIRECT_DISPATCH,Boolean.TRUE);
localClient.path("bookstore/books/123");
Book book=localClient.get(Book.class);
assertEquals(123L,book.getId());
}
InternalCallVerifier EqualityVerifier
@Test public void testProxyDirectDispatchPost() throws Exception {
BookStoreSpring localProxy=JAXRSClientFactory.create("local://books",BookStoreSpring.class);
WebClient.getConfig(localProxy).getRequestContext().put(LocalConduit.DIRECT_DISPATCH,Boolean.TRUE);
Book response=localProxy.convertBook(new Book2("New",124L));
assertEquals(124L,response.getId());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testProxyEmtpyResponse() throws Exception {
BookStore localProxy=JAXRSClientFactory.create("local://books",BookStore.class);
assertNull(localProxy.getEmptyBook());
assertEquals(204,WebClient.client(localProxy).getResponse().getStatus());
}
Class: org.apache.cxf.systest.jaxrs.JAXRSLoggingAtomPushSpringTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testManyEntries() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + PORT + "/entriesMany");
wc.path("/log").get();
Thread.sleep(3000);
List elements=Resource4.getElements();
assertEquals(4,elements.size());
resetCounters();
for ( Entry e : elements) {
LogRecords records=readLogRecords(e.getContent());
List list=records.getLogRecords();
assertNotNull(list);
assertEquals(2,list.size());
for ( org.apache.cxf.management.web.logging.LogRecord record : list) {
updateCounters(record,"Resource4");
}
}
verifyCounters();
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testFeedsWithLogRecordsExtension() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + PORT + "/extensions");
wc.path("/log").get();
Thread.sleep(3000);
List elements=Resource5.getElements();
assertEquals(8,elements.size());
resetCounters();
for ( Feed feed : elements) {
List entries=feed.getEntries();
assertEquals(1,entries.size());
Entry e=entries.get(0);
LogRecords records=readLogRecordsExtension(e);
List list=records.getLogRecords();
assertNotNull(list);
assertEquals(1,list.size());
updateCounters(list.get(0),"Resource5");
}
verifyCounters();
}
InternalCallVerifier EqualityVerifier
@Test public void testFeedsWithBatchLogRecordsOneEntry() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + PORT + "/batch");
wc.path("/log").get();
Thread.sleep(3000);
List elements=Resource2.getElements();
assertEquals(2,elements.size());
resetCounters();
for ( Feed feed : elements) {
List entries=feed.getEntries();
assertEquals(4,entries.size());
for ( Entry e : entries) {
updateCounters(readLogRecord(e.getContent()),"Resource2");
}
}
verifyCounters();
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testFeedsWithLogRecordsOneEntry() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + PORT + "/root");
try {
wc.path("/log").get();
}
catch ( Exception ex) {
}
Thread.sleep(3000);
List elements=Resource.getElements();
assertEquals(8,elements.size());
resetCounters();
for ( Feed feed : elements) {
List entries=feed.getEntries();
assertEquals(1,entries.size());
Entry e=entries.get(0);
LogRecords records=readLogRecords(e.getContent());
List list=records.getLogRecords();
assertNotNull(list);
assertEquals(1,list.size());
updateCounters(list.get(0),"Resource");
}
verifyCounters();
}
Class: org.apache.cxf.systest.jaxrs.JAXRSMultipartTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testAddBookJaxbJsonImageWebClientRelated2() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/books/jaxbimagejson";
WebClient client=WebClient.create(address);
WebClient.getConfig(client).getOutInterceptors().add(new LoggingOutInterceptor());
WebClient.getConfig(client).getInInterceptors().add(new LoggingInInterceptor());
client.type("multipart/mixed").accept("multipart/mixed");
Book jaxb=new Book("jaxb",1L);
Book json=new Book("json",2L);
InputStream is1=getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg");
Map objects=new LinkedHashMap();
MultivaluedMap headers=new MetadataMap();
headers.putSingle("Content-Type","application/xml");
headers.putSingle("Content-ID","theroot");
headers.putSingle("Content-Transfer-Encoding","customxml");
Attachment attJaxb=new Attachment(headers,jaxb);
headers=new MetadataMap();
headers.putSingle("Content-Type","application/json");
headers.putSingle("Content-ID","thejson");
headers.putSingle("Content-Transfer-Encoding","customjson");
Attachment attJson=new Attachment(headers,json);
headers=new MetadataMap();
headers.putSingle("Content-Type","application/octet-stream");
headers.putSingle("Content-ID","theimage");
headers.putSingle("Content-Transfer-Encoding","customstream");
Attachment attIs=new Attachment(headers,is1);
objects.put(MediaType.APPLICATION_XML,attJaxb);
objects.put(MediaType.APPLICATION_JSON,attJson);
objects.put(MediaType.APPLICATION_OCTET_STREAM,attIs);
Collection extends Attachment> coll=client.postAndGetCollection(objects,Attachment.class);
List result=new ArrayList(coll);
Book jaxb2=readBookFromInputStream(result.get(0).getDataHandler().getInputStream());
assertEquals("jaxb",jaxb2.getName());
assertEquals(1L,jaxb2.getId());
Book json2=readJSONBookFromInputStream(result.get(1).getDataHandler().getInputStream());
assertEquals("json",json2.getName());
assertEquals(2L,json2.getId());
InputStream is2=result.get(2).getDataHandler().getInputStream();
byte[] image1=IOUtils.readBytesFromStream(getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg"));
byte[] image2=IOUtils.readBytesFromStream(is2);
assertTrue(Arrays.equals(image1,image2));
}
InternalCallVerifier EqualityVerifier
@Test public void testAddBookAsJAXBJSONProxy() throws Exception {
MultipartStore store=JAXRSClientFactory.create("http://localhost:" + PORT,MultipartStore.class);
Book b=store.addBookJaxbJsonWithConsumes(new Book2("CXF in Action",1L),new Book("CXF in Action - 2",2L));
assertEquals(124L,b.getId());
assertEquals("CXF in Action - 2",b.getName());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testUploadImageFromForm() throws Exception {
InputStream is1=getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg");
String address="http://localhost:" + PORT + "/bookstore/books/formimage";
WebClient client=WebClient.create(address);
HTTPConduit conduit=WebClient.getConfig(client).getHttpConduit();
conduit.getClient().setReceiveTimeout(1000000);
conduit.getClient().setConnectionTimeout(1000000);
client.type("multipart/form-data").accept("multipart/form-data");
ContentDisposition cd=new ContentDisposition("attachment;filename=java.jpg");
MultivaluedMap headers=new MetadataMap();
headers.putSingle("Content-ID","image");
headers.putSingle("Content-Disposition",cd.toString());
headers.putSingle("Content-Location","http://host/bar");
headers.putSingle("custom-header","custom");
Attachment att=new Attachment(is1,headers);
MultipartBody body=new MultipartBody(att);
MultipartBody body2=client.post(body,MultipartBody.class);
InputStream is2=body2.getRootAttachment().getDataHandler().getInputStream();
byte[] image1=IOUtils.readBytesFromStream(getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg"));
byte[] image2=IOUtils.readBytesFromStream(is2);
assertTrue(Arrays.equals(image1,image2));
ContentDisposition cd2=body2.getRootAttachment().getContentDisposition();
assertEquals("attachment;filename=java.jpg",cd2.toString());
assertEquals("java.jpg",cd2.getParameter("filename"));
assertEquals("http://host/location",body2.getRootAttachment().getHeader("Content-Location"));
}
InternalCallVerifier EqualityVerifier
@Test public void testMultipartRequestNoBody() throws Exception {
PostMethod post=new PostMethod("http://localhost:" + PORT + "/bookstore/books/image");
String ct="multipart/mixed";
post.setRequestHeader("Content-Type",ct);
HttpClient httpclient=new HttpClient();
try {
int result=httpclient.executeMethod(post);
assertEquals(400,result);
}
finally {
post.releaseConnection();
}
}
InternalCallVerifier EqualityVerifier
@Test public void testUseProxyToAddBookAndSimpleParts() throws Exception {
MultipartStore store=JAXRSClientFactory.create("http://localhost:" + PORT,MultipartStore.class);
HTTPConduit conduit=WebClient.getConfig(store).getHttpConduit();
conduit.getClient().setReceiveTimeout(1000000);
Book b=store.testAddBookAndSimpleParts(new Book("CXF in Action",124L),"1",2);
assertEquals(124L,b.getId());
assertEquals("CXF in Action - 12",b.getName());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testAddGetImageWebClient() throws Exception {
InputStream is1=getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg");
String address="http://localhost:" + PORT + "/bookstore/books/image";
WebClient client=WebClient.create(address);
client.type("multipart/mixed").accept("multipart/mixed");
WebClient.getConfig(client).getRequestContext().put("support.type.as.multipart","true");
InputStream is2=client.post(is1,InputStream.class);
byte[] image1=IOUtils.readBytesFromStream(getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg"));
byte[] image2=IOUtils.readBytesFromStream(is2);
assertTrue(Arrays.equals(image1,image2));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testAddGetJaxbBooksWebClient() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/books/jaxbonly";
WebClient client=WebClient.create(address);
client.type("multipart/mixed;type=application/xml").accept("multipart/mixed");
Book b=new Book("jaxb",1L);
Book b2=new Book("jaxb2",2L);
List books=new ArrayList();
books.add(b);
books.add(b2);
Collection extends Book> coll=client.postAndGetCollection(books,Book.class);
List result=new ArrayList(coll);
Book jaxb=result.get(0);
assertEquals("jaxb",jaxb.getName());
assertEquals(1L,jaxb.getId());
Book jaxb2=result.get(1);
assertEquals("jaxb2",jaxb2.getName());
assertEquals(2L,jaxb2.getId());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testAddBookJaxbJsonImageAttachments() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/books/jaxbimagejson";
WebClient client=WebClient.create(address);
client.type("multipart/mixed").accept("multipart/mixed");
Book jaxb=new Book("jaxb",1L);
Book json=new Book("json",2L);
InputStream is1=getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg");
List objects=new ArrayList();
objects.add(new Attachment("",MediaType.APPLICATION_XML,jaxb));
objects.add(new Attachment("thejson",MediaType.APPLICATION_JSON,json));
objects.add(new Attachment("theimage",MediaType.APPLICATION_OCTET_STREAM,is1));
Collection extends Attachment> coll=client.postAndGetCollection(objects,Attachment.class);
List result=new ArrayList(coll);
Book jaxb2=readBookFromInputStream(result.get(0).getDataHandler().getInputStream());
assertEquals("jaxb",jaxb2.getName());
assertEquals(1L,jaxb2.getId());
Book json2=readJSONBookFromInputStream(result.get(1).getDataHandler().getInputStream());
assertEquals("json",json2.getName());
assertEquals(2L,json2.getId());
InputStream is2=result.get(2).getDataHandler().getInputStream();
byte[] image1=IOUtils.readBytesFromStream(getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg"));
byte[] image2=IOUtils.readBytesFromStream(is2);
assertTrue(Arrays.equals(image1,image2));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testUploadFileWithSemicolonName() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/books/file/semicolon";
WebClient client=WebClient.create(address);
client.type("multipart/form-data").accept("text/plain");
ContentDisposition cd=new ContentDisposition("attachment;name=\"a\";filename=\"a;txt\"");
MultivaluedMap headers=new MetadataMap();
headers.putSingle("Content-Disposition",cd.toString());
Attachment att=new Attachment(new ByteArrayInputStream("file name with semicolon".getBytes()),headers);
MultipartBody body=new MultipartBody(att);
String partContent=client.post(body,String.class);
assertEquals("file name with semicolon, filename:" + "a;txt",partContent);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testAddBookWebClient(){
InputStream is1=getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/add_book.txt");
String address="http://localhost:" + PORT + "/bookstore/books/jaxb";
WebClient client=WebClient.create(address);
WebClient.getConfig(client).getRequestContext().put("support.type.as.multipart","true");
client.type("multipart/related;type=text/xml").accept("text/xml");
Book book=client.post(is1,Book.class);
assertEquals("CXF in Action - 2",book.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testNullableParamsPrimitive() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/books/testnullpartprimitive";
WebClient client=WebClient.create(address);
client.type("multipart/form-data").accept("text/plain");
List atts=new LinkedList();
atts.add(new Attachment("somepart","text/plain","hello there"));
Response r=client.postCollection(atts,Attachment.class);
assertEquals(Response.Status.OK.getStatusCode(),r.getStatus());
assertEquals((Integer)0,Integer.valueOf(IOUtils.readStringFromStream((InputStream)r.getEntity())));
}
InternalCallVerifier EqualityVerifier
@Test public void testMultipartRequestTooLarge() throws Exception {
PostMethod post=new PostMethod("http://localhost:" + PORT + "/bookstore/books/image");
String ct="multipart/mixed";
post.setRequestHeader("Content-Type",ct);
Part[] parts=new Part[1];
parts[0]=new FilePart("image",new ByteArrayPartSource("testfile.png",new byte[1024 * 11]),"image/png",null);
post.setRequestEntity(new MultipartRequestEntity(parts,post.getParams()));
HttpClient httpclient=new HttpClient();
try {
int result=httpclient.executeMethod(post);
assertEquals(413,result);
}
finally {
post.releaseConnection();
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookJaxbJsonProxy() throws Exception {
String address="http://localhost:" + PORT;
MultipartStore client=JAXRSClientFactory.create(address,MultipartStore.class);
Map map=client.getBookJaxbJson();
List result=new ArrayList(map.values());
Book jaxb=result.get(0);
assertEquals("jaxb",jaxb.getName());
assertEquals(1L,jaxb.getId());
Book json=result.get(1);
assertEquals("json",json.getName());
assertEquals(2L,json.getId());
String contentType=WebClient.client(client).getResponse().getMetadata().getFirst("Content-Type").toString();
MediaType mt=MediaType.valueOf(contentType);
assertEquals("multipart",mt.getType());
assertEquals("mixed",mt.getSubtype());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testAddBookJsonImageStream() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/books/jsonimagestream";
WebClient client=WebClient.create(address);
WebClient.getConfig(client).getOutInterceptors().add(new LoggingOutInterceptor());
WebClient.getConfig(client).getInInterceptors().add(new LoggingInInterceptor());
client.type("multipart/mixed").accept("multipart/mixed");
Book json=new Book("json",1L);
InputStream is1=getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg");
Map objects=new LinkedHashMap();
MultivaluedMap headers=new MetadataMap();
headers=new MetadataMap();
headers.putSingle("Content-Type","application/json");
headers.putSingle("Content-ID","thejson");
headers.putSingle("Content-Transfer-Encoding","customjson");
Attachment attJson=new Attachment(headers,json);
headers=new MetadataMap();
headers.putSingle("Content-Type","application/octet-stream");
headers.putSingle("Content-ID","theimage");
headers.putSingle("Content-Transfer-Encoding","customstream");
Attachment attIs=new Attachment(headers,is1);
objects.put(MediaType.APPLICATION_JSON,attJson);
objects.put(MediaType.APPLICATION_OCTET_STREAM,attIs);
Collection extends Attachment> coll=client.postAndGetCollection(objects,Attachment.class);
List result=new ArrayList(coll);
assertEquals(2,result.size());
Book json2=readJSONBookFromInputStream(result.get(0).getDataHandler().getInputStream());
assertEquals("json",json2.getName());
assertEquals(1L,json2.getId());
InputStream is2=result.get(1).getDataHandler().getInputStream();
byte[] image1=IOUtils.readBytesFromStream(getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg"));
byte[] image2=IOUtils.readBytesFromStream(is2);
assertTrue(Arrays.equals(image1,image2));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testUploadImageFromForm2() throws Exception {
File file=new File(getClass().getResource("/org/apache/cxf/systest/jaxrs/resources/java.jpg").toURI().getPath());
String address="http://localhost:" + PORT + "/bookstore/books/formimage2";
WebClient client=WebClient.create(address);
client.type("multipart/form-data").accept("multipart/form-data");
WebClient.getConfig(client).getRequestContext().put("support.type.as.multipart","true");
MultipartBody body2=client.post(file,MultipartBody.class);
InputStream is2=body2.getRootAttachment().getDataHandler().getInputStream();
byte[] image1=IOUtils.readBytesFromStream(getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg"));
byte[] image2=IOUtils.readBytesFromStream(is2);
assertTrue(Arrays.equals(image1,image2));
ContentDisposition cd2=body2.getRootAttachment().getContentDisposition();
assertEquals("form-data;name=file;filename=java.jpg",cd2.toString());
assertEquals("java.jpg",cd2.getParameter("filename"));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testXopWebClient() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/xop";
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
bean.setAddress(address);
bean.setProperties(Collections.singletonMap(org.apache.cxf.message.Message.MTOM_ENABLED,(Object)"true"));
WebClient client=bean.createWebClient();
WebClient.getConfig(client).getInInterceptors().add(new LoggingInInterceptor());
WebClient.getConfig(client).getOutInterceptors().add(new LoggingOutInterceptor());
WebClient.getConfig(client).getRequestContext().put("support.type.as.multipart","true");
client.type("multipart/related").accept("multipart/related");
XopType xop=new XopType();
xop.setName("xopName");
InputStream is=getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/book.xsd");
byte[] data=IOUtils.readBytesFromStream(is);
xop.setAttachinfo(new DataHandler(new ByteArrayDataSource(data,"application/octet-stream")));
xop.setAttachInfoRef(new DataHandler(new ByteArrayDataSource(data,"application/octet-stream")));
String bookXsd=IOUtils.readStringFromStream(getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/book.xsd"));
xop.setAttachinfo2(bookXsd.getBytes());
xop.setImage(getImage("/org/apache/cxf/systest/jaxrs/resources/java.jpg"));
XopType xop2=client.post(xop,XopType.class);
String bookXsdOriginal=IOUtils.readStringFromStream(getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/book.xsd"));
String bookXsd2=IOUtils.readStringFromStream(xop2.getAttachinfo().getInputStream());
assertEquals(bookXsdOriginal,bookXsd2);
String bookXsdRef=IOUtils.readStringFromStream(xop2.getAttachInfoRef().getInputStream());
assertEquals(bookXsdOriginal,bookXsdRef);
String ctString=client.getResponse().getMetadata().getFirst("Content-Type").toString();
MediaType mt=MediaType.valueOf(ctString);
Map params=mt.getParameters();
assertEquals(4,params.size());
assertNotNull(params.get("boundary"));
assertNotNull(params.get("type"));
assertNotNull(params.get("start"));
assertNotNull(params.get("start-info"));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testBookAsRootAttachmentInputStreamReadItself() throws Exception {
String address="http://localhost:" + PORT + "/bookstore/books/istream2";
WebClient wc=WebClient.create(address);
wc.type("multipart/mixed;type=text/xml");
wc.accept("text/xml");
WebClient.getConfig(wc).getRequestContext().put("support.type.as.multipart","true");
Book book=wc.post(new Book("CXF in Action - 2",12345L),Book.class);
assertEquals(432L,book.getId());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testGetBookJaxbJsonProxy2() throws Exception {
String address="http://localhost:" + PORT;
MultipartStore client=JAXRSClientFactory.create(address,MultipartStore.class);
Map map=client.getBookJaxbJsonObject();
List result=new ArrayList(map.values());
assertEquals(2,result.size());
assertTrue(((Attachment)result.get(0)).getContentType().toString().contains("application/xml"));
assertTrue(((Attachment)result.get(1)).getContentType().toString().contains("application/json"));
}
InternalCallVerifier EqualityVerifier
@Test public void testMultipartRequestTooLargeManyParts() throws Exception {
PostMethod post=new PostMethod("http://localhost:" + PORT + "/bookstore/books/image");
String ct="multipart/mixed";
post.setRequestHeader("Content-Type",ct);
Part[] parts=new Part[2];
parts[0]=new FilePart("image",new ByteArrayPartSource("testfile.png",new byte[1024 * 9]),"image/png",null);
parts[1]=new FilePart("image",new ByteArrayPartSource("testfile2.png",new byte[1024 * 11]),"image/png",null);
post.setRequestEntity(new MultipartRequestEntity(parts,post.getParams()));
HttpClient httpclient=new HttpClient();
try {
int result=httpclient.executeMethod(post);
assertEquals(413,result);
}
finally {
post.releaseConnection();
}
}
InternalCallVerifier EqualityVerifier
@Test public void testAddBookAsJAXBOnlyProxy() throws Exception {
MultipartStore store=JAXRSClientFactory.create("http://localhost:" + PORT,MultipartStore.class);
Book2 b=store.addBookJaxbOnlyWithConsumes(new Book2("CXF in Action",1L));
assertEquals(1L,b.getId());
assertEquals("CXF in Action",b.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookJsonProxy() throws Exception {
String address="http://localhost:" + PORT;
MultipartStore client=JAXRSClientFactory.create(address,MultipartStore.class);
Map map=client.getBookJson();
List result=new ArrayList(map.values());
assertEquals(1,result.size());
Book json=result.get(0);
assertEquals("json",json.getName());
assertEquals(1L,json.getId());
String contentType=WebClient.client(client).getResponse().getMetadata().getFirst("Content-Type").toString();
MediaType mt=MediaType.valueOf(contentType);
assertEquals("multipart",mt.getType());
assertEquals("mixed",mt.getSubtype());
}
Class: org.apache.cxf.systest.jaxrs.JAXRSOverlappingDestinationsTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testAbsolutePathOneAndTwo() throws Exception {
final String requestURI="http://localhost:" + PORT + "/one/bookstore/request?delay";
Callable callable=new Callable(){
public String call(){
WebClient wc=WebClient.create(requestURI);
return wc.accept("text/plain").get(String.class);
}
}
;
FutureTask task=new FutureTask(callable);
ExecutorService executor=Executors.newFixedThreadPool(1);
executor.execute(task);
Thread.sleep(1000);
Runnable runnable=new Runnable(){
public void run(){
try {
testAbsolutePathTwo();
}
catch ( Exception ex) {
throw new RuntimeException("Concurrent testAbsolutePathTwo failed");
}
}
}
;
new Thread(runnable).start();
Thread.sleep(2000);
String path=task.get();
assertEquals("Absolute RequestURI is wrong",requestURI,path);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testAbsolutePathOneAndTwoWithLock() throws Exception {
WebClient.create("http://localhost:" + PORT + "/one/bookstore/lock").accept("text/plain").get();
final String requestURI="http://localhost:" + PORT + "/one/bookstore/uris";
Callable callable=new Callable(){
public String call(){
WebClient wc=WebClient.create(requestURI);
return wc.accept("text/plain").get(String.class);
}
}
;
FutureTask task=new FutureTask(callable);
ExecutorService executor=Executors.newFixedThreadPool(1);
executor.execute(task);
Thread.sleep(3000);
WebClient wc2=WebClient.create("http://localhost:" + PORT + "/two/bookstore/unlock");
wc2.accept("text/plain").get();
String path=task.get();
assertEquals("Absolute RequestURI is wrong",requestURI,path);
}
InternalCallVerifier EqualityVerifier
@Test public void testAbsolutePathTwo() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + PORT + "/two/bookstore/request");
String path=wc.accept("text/plain").get(String.class);
assertEquals("Absolute RequestURI is wrong",wc.getBaseURI().toString(),path);
}
InternalCallVerifier EqualityVerifier
@Test public void testAbsolutePathOne() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + PORT + "/one/bookstore/request");
String path=wc.accept("text/plain").get(String.class);
assertEquals("Absolute RequestURI is wrong",wc.getBaseURI().toString(),path);
}
Class: org.apache.cxf.systest.jaxrs.JAXRSRequestDispatcherTest APIUtilityVerifier BooleanVerifier InternalCallVerifier IgnoredMethod HybridVerifier
@Test @Ignore("JSP pages need to be precompiled by Maven build") public void testGetBookJSPRequestScope() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/the/bookstore2/books/html/123";
WebClient client=WebClient.create(endpointAddress);
client.accept("text/html");
WebClient.getConfig(client).getHttpConduit().getClient().setReceiveTimeout(100000000);
String data=client.accept("text/html").get(String.class);
assertTrue(data.contains("Request Book 123 "));
assertTrue(data.contains("CXF in Action "));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetTextWelcomeFile() throws Exception {
String address="http://localhost:" + PORT + "/welcome2/welcome.txt";
WebClient client=WebClient.create(address);
client.accept("text/plain");
String welcome=client.get(String.class);
System.out.println(welcome);
assertEquals("Welcome",welcome);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookHTMLFromDefaultServlet() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/the/bookstore4/books/html/123";
WebClient client=WebClient.create(endpointAddress);
client.accept("text/html");
WebClient.getConfig(client).getHttpConduit().getClient().setReceiveTimeout(100000000);
XMLSource source=client.accept("text/html").get(XMLSource.class);
Map namespaces=new HashMap();
namespaces.put("xhtml","http://www.w3.org/1999/xhtml");
namespaces.put("books","http://www.w3.org/books");
String value=source.getValue("xhtml:html/xhtml:body/xhtml:ul/books:bookTag",namespaces);
assertEquals("CXF Rocks",value);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier IgnoredMethod HybridVerifier
@Test @Ignore("JSP pages need to be precompiled by Maven build") public void testGetBookJSPSessionScope() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/the/bookstore3/books/html/456";
WebClient client=WebClient.create(endpointAddress);
client.accept("text/html");
WebClient.getConfig(client).getHttpConduit().getClient().setReceiveTimeout(100000000);
String data=client.accept("text/html").get(String.class);
assertTrue(data.contains("Session Book 456 "));
assertTrue(data.contains("CXF in Action "));
}
Class: org.apache.cxf.systest.jaxrs.JAXRSServletFilterTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testServletConfigInitParam() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/webapp/filter/resources/servlet/config/query?name=a";
WebClient wc=WebClient.create(endpointAddress);
WebClient.getConfig(wc).getHttpConduit().getClient().setReceiveTimeout(1000000L);
wc.accept("text/plain");
assertEquals("avalue",wc.get(String.class));
}
Class: org.apache.cxf.systest.jaxrs.JAXRSSimpleRequestDispatcherTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetTextWelcomeFile() throws Exception {
String address="http://localhost:" + PORT + "/dispatch/welcome.txt";
WebClient client=WebClient.create(address);
client.accept("text/plain");
String welcome=client.get(String.class);
assertEquals("Welcome",welcome);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetRedirectedBook() throws Exception {
String address="http://localhost:" + PORT + "/dispatch/bookstore2/books/redirectStart";
WebClient client=WebClient.create(address);
WebClient.getConfig(client).getHttpConduit().getClient().setReceiveTimeout(10000000L);
client.accept("application/json");
Book book=client.get(Book.class);
assertEquals("Redirect complete: /dispatch/bookstore/books/redirectComplete",book.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetRedirectedBook2() throws Exception {
String address="http://localhost:" + PORT + "/dispatch/redirect/bookstore3/books/redirectStart";
WebClient client=WebClient.create(address);
WebClient.getConfig(client).getHttpConduit().getClient().setReceiveTimeout(10000000L);
client.accept("application/json");
Book book=client.get(Book.class);
assertEquals("Redirect complete: /dispatch/redirect/bookstore/books/redirectComplete",book.getName());
}
Class: org.apache.cxf.systest.jaxrs.JAXRSSoapBookTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testPostBookTransform() throws Exception {
String address="http://localhost:" + PORT + "/test/v1/rest-transform/bookstore/books";
TransformOutInterceptor out=new TransformOutInterceptor();
out.setOutTransformElements(Collections.singletonMap("{http://www.example.org/books}*","{http://www.example.org/super-books}*"));
TransformInInterceptor in=new TransformInInterceptor();
Map map=new HashMap();
map.put("TheBook","{http://www.example.org/books}Book");
map.put("id","{http://www.example.org/books}id");
in.setInTransformElements(map);
WebClient client=WebClient.create(address);
WebClient.getConfig(client).getInInterceptors().add(in);
WebClient.getConfig(client).getOutInterceptors().add(out);
Book2 book=client.accept("text/xml").post(new Book2(),Book2.class);
assertEquals(124L,book.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testPostGetBookFastinfosetProxy() throws Exception {
JAXBElementProvider p=new JAXBElementProvider();
p.setConsumeMediaTypes(Collections.singletonList("application/fastinfoset"));
p.setProduceMediaTypes(Collections.singletonList("application/fastinfoset"));
BookStoreJaxrsJaxws client=JAXRSClientFactory.create("http://localhost:" + PORT + "/test/services/rest4",BookStoreSoapRestFastInfoset2.class,Collections.singletonList(p));
Book b=new Book("CXF",1L);
Book b2=client.addFastinfoBook(b);
assertEquals(b2.getName(),b.getName());
assertEquals(b2.getId(),b.getId());
checkFiInterceptors(WebClient.getConfig(client));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testAddOrderFormBean() throws Exception {
String baseAddress="http://localhost:" + PORT + "/test/services/rest";
BookStoreJaxrsJaxws proxy=JAXRSClientFactory.create(baseAddress,BookStoreJaxrsJaxws.class);
WebClient.getConfig(proxy).getOutInterceptors().add(new LoggingOutInterceptor());
WebClient.getConfig(proxy).getInInterceptors().add(new LoggingInInterceptor());
BookSubresource bs=proxy.getBookSubresource("139");
OrderBean order=new OrderBean();
order.setId(123L);
order.setWeight(100);
order.setCustomerTitle(OrderBean.Title.MS);
OrderBean order2=bs.addOrder(order);
assertEquals(Long.valueOf(123L),Long.valueOf(order2.getId()));
assertEquals(OrderBean.Title.MS,order2.getCustomerTitle());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetBookSoap() throws Exception {
String wsdlAddress="http://localhost:" + PORT + "/test/services/soap/bookservice?wsdl";
URL wsdlUrl=new URL(wsdlAddress);
BookSoapService service=new BookSoapService(wsdlUrl,new QName("http://books.com","BookService"));
BookStoreJaxrsJaxws store=service.getBookPort();
Book book=store.getBook(new Long(123));
assertEquals("id is wrong",book.getId(),123);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testNoBookWebClient() throws Exception {
String baseAddress="http://localhost:" + PORT + "/test/services/rest";
WebClient client=WebClient.create(baseAddress);
client.path("/bookstore/books/0/subresource").accept(MediaType.APPLICATION_XML_TYPE);
Book b=client.get(Book.class);
assertNull(b);
assertEquals(204,client.getResponse().getStatus());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookSubresourceParamExtensions2() throws Exception {
String baseAddress="http://localhost:" + PORT + "/test/services/rest";
BookStoreJaxrsJaxws proxy=JAXRSClientFactory.create(baseAddress,BookStoreJaxrsJaxws.class);
WebClient.getConfig(proxy).getOutInterceptors().add(new LoggingOutInterceptor());
BookSubresource bs=proxy.getBookSubresource("139");
BookBean bean=new BookBean("CXF Rocks",139L);
bean.getComments().put(1L,"Good");
bean.getComments().put(2L,"Good");
BookBean b=bs.getTheBookQueryBean(bean);
assertEquals(139,b.getId());
assertEquals("CXF Rocks",b.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookSubresourceWebClientParamExtensions() throws Exception {
WebClient client=WebClient.create("http://localhost:" + PORT + "/test/services/rest");
client.type(MediaType.TEXT_PLAIN_TYPE).accept(MediaType.APPLICATION_XML_TYPE);
client.path("/bookstore/books/139/subresource4/139/CXF Rocks");
Book bean=new Book("CXF Rocks",139L);
Form form=new Form();
form.param("name","CXF Rocks").param("id",Long.toString(139L));
Book b=readBook((InputStream)client.matrix("",bean).query("",bean).form(form).getEntity());
assertEquals(139,b.getId());
assertEquals("CXF Rocks",b.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookSubresourceClientWithContext() throws Exception {
String baseAddress="http://localhost:" + PORT + "/test/services/rest";
BookStoreJaxrsJaxws proxy=JAXRSClientFactory.create(baseAddress,BookStoreJaxrsJaxws.class);
BookSubresource bs=proxy.getBookSubresource("125");
Book b=bs.getTheBookWithContext(null);
assertEquals(125,b.getId());
assertEquals("CXF in Action",b.getName());
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testAddFeatureToClient() throws Exception {
String baseAddress="http://localhost:" + PORT + "/test/services/rest";
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
bean.setAddress(baseAddress);
bean.setResourceClass(BookStoreJaxrsJaxws.class);
TestFeature testFeature=new TestFeature();
List features=new ArrayList();
features.add(testFeature);
bean.setFeatures(features);
BookStoreJaxrsJaxws proxy=(BookStoreJaxrsJaxws)bean.create();
Book b=proxy.getBook(new Long("123"));
assertTrue("Out Interceptor not invoked",testFeature.handleMessageOnOutInterceptorCalled());
assertTrue("In Interceptor not invoked",testFeature.handleMessageOnInInterceptorCalled());
assertEquals(123,b.getId());
assertEquals("CXF in Action",b.getName());
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testAddGetBook123Client() throws Exception {
String baseAddress="http://localhost:" + PORT + "/test/services/rest";
BookStoreJaxrsJaxws proxy=JAXRSClientFactory.create(baseAddress,BookStoreJaxrsJaxws.class);
Book b=new Book();
b.setId(124);
b.setName("CXF in Action - 2");
Book b2=proxy.addBook(b);
assertNotSame(b,b2);
assertEquals(124,b2.getId());
assertEquals("CXF in Action - 2",b2.getName());
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testAddGetBook123WebClient() throws Exception {
String baseAddress="http://localhost:" + PORT + "/test/services/rest";
WebClient client=WebClient.create(baseAddress);
client.path("/bookstore/books").accept(MediaType.APPLICATION_XML_TYPE).type(MediaType.APPLICATION_XML_TYPE);
Book b=new Book();
b.setId(124);
b.setName("CXF in Action - 2");
Book b2=client.post(b,Book.class);
assertNotSame(b,b2);
assertEquals(124,b2.getId());
assertEquals("CXF in Action - 2",b2.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookWebClientForm2() throws Exception {
String baseAddress="http://localhost:" + PORT + "/test/services/rest/bookstore/books/679/subresource3";
WebClient wc=WebClient.create(baseAddress);
Form f=new Form(new MetadataMap());
f.param("id","679").param("name","CXF in Action - ").param("name","679");
Book b=readBook((InputStream)wc.accept("application/xml").form(f).getEntity());
assertEquals(679,b.getId());
assertEquals("CXF in Action - 679",b.getName());
}
UtilityVerifier BooleanVerifier InternalCallVerifier HybridVerifier
@Test public void testClientFaultOutInterceptor() throws Exception {
String baseAddress="http://localhost:" + PORT + "/test/services/rest";
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
bean.setAddress(baseAddress);
bean.setResourceClass(BookStoreJaxrsJaxws.class);
final boolean addBadOutInterceptor=true;
TestFeature testFeature=new TestFeature(addBadOutInterceptor);
List features=new ArrayList();
features.add(testFeature);
bean.setFeatures(features);
BookStoreJaxrsJaxws proxy=(BookStoreJaxrsJaxws)bean.create();
try {
proxy.getBook(new Long("123"));
fail("Method should have thrown an exception");
}
catch ( Exception e) {
assertTrue("Out Interceptor not invoked",testFeature.handleMessageOnOutInterceptorCalled());
assertTrue("In Interceptor not invoked",!testFeature.handleMessageOnInInterceptorCalled());
assertTrue("Wrong exception caught","fault from bad interceptor".equals(e.getCause().getMessage()));
assertTrue("Client In Fault In Interceptor was invoked",testFeature.faultInInterceptorCalled());
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookSubresourceParamOrder() throws Exception {
String baseAddress="http://localhost:" + PORT + "/test/services/rest";
BookStoreJaxrsJaxws proxy=JAXRSClientFactory.create(baseAddress,BookStoreJaxrsJaxws.class);
BookSubresource bs=proxy.getBookSubresource("139");
Book b=bs.getTheBook5("CXF",555L);
assertEquals(555,b.getId());
assertEquals("CXF",b.getName());
}
InternalCallVerifier EqualityVerifier
@Test public void testNoBook357WebClient() throws Exception {
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
Map properties=new HashMap();
properties.put("org.apache.cxf.http.throw_io_exceptions",Boolean.TRUE);
bean.setProperties(properties);
bean.setAddress("http://localhost:" + PORT + "/test/services/rest/bookstore/356");
WebClient wc=bean.createWebClient();
Response response=wc.get();
assertEquals(404,response.getStatus());
String msg=IOUtils.readStringFromStream((InputStream)response.getEntity());
assertEquals("No Book with id 356 is available",msg);
}
InternalCallVerifier EqualityVerifier
@Test public void testAddGetBookRest() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/test/services/rest/bookstore/books";
File input=new File(getClass().getResource("resources/add_book.txt").toURI());
PostMethod post=new PostMethod(endpointAddress);
post.setRequestHeader("Content-Type","application/xml");
RequestEntity entity=new FileRequestEntity(input,"text/xml; charset=ISO-8859-1");
post.setRequestEntity(entity);
HttpClient httpclient=new HttpClient();
try {
int result=httpclient.executeMethod(post);
assertEquals(200,result);
InputStream expected=getClass().getResourceAsStream("resources/expected_add_book.txt");
assertEquals(stripXmlInstructionIfNeeded(getStringFromInputStream(expected)),stripXmlInstructionIfNeeded(post.getResponseBodyAsString()));
}
finally {
post.releaseConnection();
}
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testGetBook123Client() throws Exception {
String baseAddress="http://localhost:" + PORT + "/test/services/rest";
BookStoreJaxrsJaxws proxy=JAXRSClientFactory.create(baseAddress,BookStoreJaxrsJaxws.class);
HTTPConduit conduit=(HTTPConduit)WebClient.getConfig(proxy).getConduit();
Book b=proxy.getBook(new Long("123"));
assertEquals(123,b.getId());
assertEquals("CXF in Action",b.getName());
HTTPConduit conduit2=(HTTPConduit)WebClient.getConfig(proxy).getConduit();
assertSame(conduit,conduit2);
conduit.getClient().setAutoRedirect(true);
b=proxy.getBook(new Long("123"));
assertEquals(123,b.getId());
assertEquals("CXF in Action",b.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBook123WebClientResponse() throws Exception {
String baseAddress="http://localhost:" + PORT + "/test/services/rest";
WebClient client=WebClient.create(baseAddress);
client.path("/bookstore/123").accept(MediaType.APPLICATION_XML_TYPE);
Book b=readBook((InputStream)client.get().getEntity());
assertEquals(123,b.getId());
assertEquals("CXF in Action",b.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookSubresourceClient() throws Exception {
String baseAddress="http://localhost:" + PORT + "/test/services/rest";
BookStoreJaxrsJaxws proxy=JAXRSClientFactory.create(baseAddress,BookStoreJaxrsJaxws.class);
BookSubresource bs=proxy.getBookSubresource("125");
Book b=bs.getTheBook();
assertEquals(125,b.getId());
assertEquals("CXF in Action",b.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookSubresourceClientFormParam() throws Exception {
String baseAddress="http://localhost:" + PORT + "/test/services/rest";
BookStoreJaxrsJaxws proxy=JAXRSClientFactory.create(baseAddress,BookStoreJaxrsJaxws.class);
BookSubresource bs=proxy.getBookSubresource("679");
List parts=new ArrayList();
parts.add("CXF in Action - ");
parts.add(Integer.toString(679));
Book b=bs.getTheBook3("679",parts);
assertEquals(679,b.getId());
assertEquals("CXF in Action - 679",b.getName());
}
InternalCallVerifier EqualityVerifier
@Test public void testOtherInterceptorDrainingStream() throws Exception {
String baseAddress="http://localhost:" + PORT + "/test/services/rest";
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
bean.setAddress(baseAddress);
bean.getInInterceptors().add(new TestStreamDrainInterptor());
WebClient client=bean.createWebClient();
client.path("/bookstore/123").accept(MediaType.APPLICATION_XML_TYPE);
Book b=client.get(Book.class);
assertEquals(123,b.getId());
assertEquals("CXF in Action",b.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testPostGetBookFastinfosetProxyInterceptors() throws Exception {
JAXBElementProvider p=new JAXBElementProvider();
p.setConsumeMediaTypes(Collections.singletonList("application/fastinfoset"));
p.setProduceMediaTypes(Collections.singletonList("application/fastinfoset"));
BookStoreJaxrsJaxws client=JAXRSClientFactory.create("http://localhost:" + PORT + "/test/services/rest5",BookStoreSoapRestFastInfoset3.class,Collections.singletonList(p));
Book b=new Book("CXF",1L);
Map props=WebClient.getConfig(client).getRequestContext();
props.put(FIStaxOutInterceptor.FI_ENABLED,Boolean.TRUE);
Book b2=client.addFastinfoBook(b);
assertEquals(b2.getName(),b.getName());
assertEquals(b2.getId(),b.getId());
checkFiInterceptors(WebClient.getConfig(client));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookWebClientForm() throws Exception {
String baseAddress="http://localhost:" + PORT + "/test/services/rest/bookstore/books/679/subresource3";
WebClient wc=WebClient.create(baseAddress);
MultivaluedMap map=new MetadataMap();
map.putSingle("id","679");
map.add("name","CXF in Action - ");
map.add("name","679");
Book b=readBook((InputStream)wc.accept("application/xml").form(map).getEntity());
assertEquals(679,b.getId());
assertEquals("CXF in Action - 679",b.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBook123XMLSource() throws Exception {
String baseAddress="http://localhost:" + PORT + "/test/services/rest";
WebClient client=WebClient.create(baseAddress);
client.path("/bookstore/123").accept(MediaType.APPLICATION_XML_TYPE);
XMLSource source=client.get(XMLSource.class);
source.setBuffering();
Book b=source.getNode("/Book",Book.class);
assertEquals(123,b.getId());
assertEquals("CXF in Action",b.getName());
b=source.getNode("/Book",Book.class);
assertEquals(123,b.getId());
assertEquals("CXF in Action",b.getName());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetBookFastinfoset() throws Exception {
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
bean.setAddress("http://localhost:" + PORT + "/test/services/rest3/bookstore/fastinfoset2");
bean.getInInterceptors().add(new FIStaxInInterceptor());
JAXBElementProvider> p=new JAXBElementProvider();
p.setConsumeMediaTypes(Collections.singletonList("application/fastinfoset"));
bean.setProvider(p);
Map props=new HashMap();
props.put(FIStaxInInterceptor.FI_GET_SUPPORTED,Boolean.TRUE);
bean.setProperties(props);
WebClient client=bean.createWebClient();
Book b=client.accept("application/fastinfoset").get(Book.class);
assertEquals("CXF2",b.getName());
assertEquals(2L,b.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookSubresourceParamExtensions() throws Exception {
String baseAddress="http://localhost:" + PORT + "/test/services/rest";
BookStoreJaxrsJaxws proxy=JAXRSClientFactory.create(baseAddress,BookStoreJaxrsJaxws.class);
WebClient.getConfig(proxy).getOutInterceptors().add(new LoggingOutInterceptor());
BookSubresource bs=proxy.getBookSubresource("139");
Book bean=new Book("CXF Rocks",139L);
Book b=bs.getTheBook4(bean,bean,bean,bean);
assertEquals(139,b.getId());
assertEquals("CXF Rocks",b.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookSubresourceClientNoProduces() throws Exception {
String baseAddress="http://localhost:" + PORT + "/test/services/rest";
BookStoreJaxrsJaxws proxy=JAXRSClientFactory.create(baseAddress,BookStoreJaxrsJaxws.class);
BookSubresource bs=proxy.getBookSubresource("125");
Book b=bs.getTheBookNoProduces();
assertEquals(125,b.getId());
assertEquals("CXF in Action",b.getName());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetUnqualifiedBookSoap() throws Exception {
String wsdlAddress="http://localhost:" + PORT + "/test/services/soap-transform/bookservice?wsdl";
BookSoapService service=new BookSoapService(new URL(wsdlAddress),new QName("http://books.com","BookService"));
BookStoreJaxrsJaxws store=service.getBookPort();
TransformOutInterceptor out=new TransformOutInterceptor();
Map mapOut=new HashMap();
mapOut.put("{http://jaxws.jaxrs.systest.cxf.apache.org/}*","*");
out.setOutTransformElements(mapOut);
TransformInInterceptor in=new TransformInInterceptor();
Map mapIn=new HashMap();
mapIn.put("getBookResponse","{http://jaxws.jaxrs.systest.cxf.apache.org/}getBookResponse");
in.setInTransformElements(mapIn);
Client cl=ClientProxy.getClient(store);
((HTTPConduit)cl.getConduit()).getClient().setReceiveTimeout(10000000);
cl.getInInterceptors().add(in);
cl.getOutInterceptors().add(out);
Book book=store.getBook(new Long(123));
assertEquals("id is wrong",book.getId(),123);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testPostBookTransformV2() throws Exception {
String address="http://localhost:" + PORT + "/test/v2/rest-transform/bookstore/books";
WebClient client=WebClient.create(address);
Book book=client.accept("text/xml").post(new Book(),Book.class);
assertEquals(124L,book.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookSubresourceWebClientProxy2() throws Exception {
WebClient client=WebClient.create("http://localhost:" + PORT + "/test/services/rest/bookstore").path("/books/378");
client.type(MediaType.TEXT_PLAIN_TYPE).accept(MediaType.APPLICATION_XML_TYPE);
BookSubresource proxy=JAXRSClientFactory.fromClient(client,BookSubresource.class);
Book b=proxy.getTheBook2("CXF ","in ","Acti","on ","- 3","7","8");
assertEquals(378,b.getId());
assertEquals("CXF in Action - 378",b.getName());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testGetBookTransform() throws Exception {
String address="http://localhost:" + PORT + "/test/v1/rest-transform/bookstore/books/123";
WebClient client=WebClient.create(address);
Response r=client.get();
String str=getStringFromInputStream((InputStream)r.getEntity());
assertTrue(str.contains("TheBook"));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBook123WebClient() throws Exception {
String baseAddress="http://localhost:" + PORT + "/test/services/rest";
WebClient client=WebClient.create(baseAddress);
client.path("/bookstore/123").accept(MediaType.APPLICATION_XML_TYPE);
Book b=client.get(Book.class);
assertEquals(123,b.getId());
assertEquals("CXF in Action",b.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testPostGetBookFastinfoset() throws Exception {
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
bean.setAddress("http://localhost:" + PORT + "/test/services/rest3/bookstore/fastinfoset");
bean.getOutInterceptors().add(new FIStaxOutInterceptor());
bean.getInInterceptors().add(new FIStaxInInterceptor());
JAXBElementProvider> p=new JAXBElementProvider();
p.setConsumeMediaTypes(Collections.singletonList("application/fastinfoset"));
p.setProduceMediaTypes(Collections.singletonList("application/fastinfoset"));
bean.setProvider(p);
Map props=new HashMap();
props.put(FIStaxOutInterceptor.FI_ENABLED,Boolean.TRUE);
bean.setProperties(props);
WebClient client=bean.createWebClient();
Book b=new Book("CXF",1L);
Book b2=client.type("application/fastinfoset").accept("application/fastinfoset").post(b,Book.class);
assertEquals(b2.getName(),b.getName());
assertEquals(b2.getId(),b.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testCheckBookClientErrorResponse(){
String baseAddress="http://localhost:" + PORT + "/test/services/rest";
BookStoreJaxrsJaxws proxy=JAXRSClientFactory.create(baseAddress,BookStoreJaxrsJaxws.class,Collections.singletonList(new DummyResponseExceptionMapper()));
Response response=proxy.checkBook(100L);
assertEquals(HttpStatus.SC_NOT_FOUND,response.getStatus());
}
Class: org.apache.cxf.systest.jaxrs.cdi.AbstractCDITest InternalCallVerifier EqualityVerifier
@Test public void testAddOneBookWithValidation(){
final String id=UUID.randomUUID().toString();
Response r=createWebClient("/rest/custom/bookstore/books").post(new Form().param("id",id));
assertEquals(Status.BAD_REQUEST.getStatusCode(),r.getStatus());
}
InternalCallVerifier EqualityVerifier
@Test public void testInjectedVersionIsProperlyReturned(){
Response r=createWebClient("/rest/api/bookstore/version",MediaType.TEXT_PLAIN).get();
assertEquals(Status.OK.getStatusCode(),r.getStatus());
assertEquals("1.0",r.readEntity(String.class));
}
InternalCallVerifier EqualityVerifier
@Test public void testAddAndQueryOneBook(){
final String id=UUID.randomUUID().toString();
Response r=createWebClient("/rest/api/bookstore/books").post(new Form().param("id",id).param("name","Book 1234"));
assertEquals(Status.CREATED.getStatusCode(),r.getStatus());
r=createWebClient("/rest/api/bookstore/books").path(id).get();
assertEquals(Status.OK.getStatusCode(),r.getStatus());
Book book=r.readEntity(Book.class);
assertEquals(id,book.getId());
}
Class: org.apache.cxf.systest.jaxrs.cors.CrossOriginSimpleTest InternalCallVerifier EqualityVerifier
@Test public void testAnnotatedLocalPreflightNoGo() throws Exception {
configureAllowOrigins(true,null);
String r=configClient.replacePath("/setAllowCredentials/false").accept("text/plain").post(null,String.class);
assertEquals("ok",r);
HttpClient httpclient=HttpClientBuilder.create().build();
HttpOptions http=new HttpOptions("http://localhost:" + PORT + "/antest/delete");
http.addHeader("Origin","http://area51.mil:4444");
http.addHeader(CorsHeaderConstants.HEADER_AC_REQUEST_METHOD,"DELETE");
HttpResponse response=httpclient.execute(http);
assertEquals(200,response.getStatusLine().getStatusCode());
assertOriginResponse(false,new String[]{"http://area51.mil:4444"},false,response);
if (httpclient instanceof Closeable) {
((Closeable)httpclient).close();
}
}
InternalCallVerifier EqualityVerifier
@Test public void testAnnotatedClassCorrectOrigin() throws Exception {
HttpClient httpclient=HttpClientBuilder.create().build();
HttpGet httpget=new HttpGet("http://localhost:" + PORT + "/antest/simpleGet/HelloThere");
httpget.addHeader("Origin","http://area51.mil:31415");
HttpResponse response=httpclient.execute(httpget);
assertEquals(200,response.getStatusLine().getStatusCode());
HttpEntity entity=response.getEntity();
String e=IOUtils.toString(entity.getContent(),"utf-8");
assertEquals("HelloThere",e);
assertOriginResponse(false,new String[]{"http://area51.mil:31415"},true,response);
if (httpclient instanceof Closeable) {
((Closeable)httpclient).close();
}
}
InternalCallVerifier EqualityVerifier
@Test public void testAnnotatedMethodPreflight() throws Exception {
configureAllowOrigins(true,null);
String r=configClient.replacePath("/setAllowCredentials/false").accept("text/plain").post(null,String.class);
assertEquals("ok",r);
HttpClient httpclient=HttpClientBuilder.create().build();
HttpOptions http=new HttpOptions("http://localhost:" + PORT + "/untest/annotatedPut");
http.addHeader("Origin","http://area51.mil:31415");
http.addHeader(CorsHeaderConstants.HEADER_AC_REQUEST_METHOD,"PUT");
http.addHeader(CorsHeaderConstants.HEADER_AC_REQUEST_HEADERS,"X-custom-1, x-custom-2");
HttpResponse response=httpclient.execute(http);
assertEquals(200,response.getStatusLine().getStatusCode());
assertOriginResponse(false,new String[]{"http://area51.mil:31415"},true,response);
assertAllowCredentials(response,true);
List exposeHeadersValues=headerValues(response.getHeaders(CorsHeaderConstants.HEADER_AC_EXPOSE_HEADERS));
assertEquals(Collections.emptyList(),exposeHeadersValues);
List allowHeadersValues=headerValues(response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_HEADERS));
assertEquals(Arrays.asList(new String[]{"X-custom-1","x-custom-2"}),allowHeadersValues);
if (httpclient instanceof Closeable) {
((Closeable)httpclient).close();
}
}
InternalCallVerifier EqualityVerifier
@Test public void testAnnotatedSimple() throws Exception {
configureAllowOrigins(true,null);
String r=configClient.replacePath("/setAllowCredentials/false").accept("text/plain").post(null,String.class);
assertEquals("ok",r);
HttpClient httpclient=HttpClientBuilder.create().build();
HttpGet httpget=new HttpGet("http://localhost:" + PORT + "/untest/annotatedGet/HelloThere");
httpget.addHeader("Origin","http://area51.mil:31415");
HttpResponse response=httpclient.execute(httpget);
assertEquals(200,response.getStatusLine().getStatusCode());
assertOriginResponse(false,new String[]{"http://area51.mil:31415"},true,response);
assertAllowCredentials(response,false);
List exposeHeadersValues=headerValues(response.getHeaders(CorsHeaderConstants.HEADER_AC_EXPOSE_HEADERS));
assertEquals(Arrays.asList(new String[]{"X-custom-3","X-custom-4"}),exposeHeadersValues);
if (httpclient instanceof Closeable) {
((Closeable)httpclient).close();
}
}
InternalCallVerifier EqualityVerifier
@Test public void testAnnotatedMethodPreflight2() throws Exception {
configureAllowOrigins(true,null);
String r=configClient.replacePath("/setAllowCredentials/false").accept("text/plain").post(null,String.class);
assertEquals("ok",r);
HttpClient httpclient=HttpClientBuilder.create().build();
HttpOptions http=new HttpOptions("http://localhost:" + PORT + "/untest/annotatedPut2");
http.addHeader("Origin","http://area51.mil:31415");
http.addHeader(CorsHeaderConstants.HEADER_AC_REQUEST_METHOD,"PUT");
http.addHeader(CorsHeaderConstants.HEADER_AC_REQUEST_HEADERS,"X-custom-1, x-custom-2");
HttpResponse response=httpclient.execute(http);
assertEquals(200,response.getStatusLine().getStatusCode());
assertOriginResponse(false,new String[]{"http://area51.mil:31415"},true,response);
assertAllowCredentials(response,true);
List exposeHeadersValues=headerValues(response.getHeaders(CorsHeaderConstants.HEADER_AC_EXPOSE_HEADERS));
assertEquals(Collections.emptyList(),exposeHeadersValues);
List allowHeadersValues=headerValues(response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_HEADERS));
assertEquals(Arrays.asList(new String[]{"X-custom-1","x-custom-2"}),allowHeadersValues);
if (httpclient instanceof Closeable) {
((Closeable)httpclient).close();
}
}
InternalCallVerifier EqualityVerifier
@Test public void preflightPostClassAnnotationPass() throws ClientProtocolException, IOException {
HttpClient httpclient=HttpClientBuilder.create().build();
HttpOptions httpoptions=new HttpOptions("http://localhost:" + PORT + "/antest/unannotatedPost");
httpoptions.addHeader("Origin","http://area51.mil:31415");
httpoptions.addHeader("Content-Type","application/json");
httpoptions.addHeader(CorsHeaderConstants.HEADER_AC_REQUEST_METHOD,"POST");
httpoptions.addHeader(CorsHeaderConstants.HEADER_AC_REQUEST_HEADERS,"X-custom-1");
HttpResponse response=httpclient.execute(httpoptions);
assertEquals(200,response.getStatusLine().getStatusCode());
Header[] origin=response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_ORIGIN);
assertEquals(1,origin.length);
assertEquals("http://area51.mil:31415",origin[0].getValue());
Header[] method=response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_METHODS);
assertEquals(1,method.length);
assertEquals("POST",method[0].getValue());
Header[] requestHeaders=response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_HEADERS);
assertEquals(1,requestHeaders.length);
assertEquals("X-custom-1",requestHeaders[0].getValue());
if (httpclient instanceof Closeable) {
((Closeable)httpclient).close();
}
}
InternalCallVerifier EqualityVerifier
@Test public void testAnnotatedLocalPreflight() throws Exception {
configureAllowOrigins(true,null);
String r=configClient.replacePath("/setAllowCredentials/false").accept("text/plain").post(null,String.class);
assertEquals("ok",r);
HttpClient httpclient=HttpClientBuilder.create().build();
HttpOptions http=new HttpOptions("http://localhost:" + PORT + "/antest/delete");
http.addHeader("Origin","http://area51.mil:3333");
http.addHeader(CorsHeaderConstants.HEADER_AC_REQUEST_METHOD,"DELETE");
HttpResponse response=httpclient.execute(http);
assertEquals(200,response.getStatusLine().getStatusCode());
assertOriginResponse(false,new String[]{"http://area51.mil:3333"},true,response);
assertAllowCredentials(response,false);
List exposeHeadersValues=headerValues(response.getHeaders(CorsHeaderConstants.HEADER_AC_EXPOSE_HEADERS));
assertEquals(Collections.emptyList(),exposeHeadersValues);
List allowedMethods=headerValues(response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_METHODS));
assertEquals(Arrays.asList("DELETE PUT"),allowedMethods);
if (httpclient instanceof Closeable) {
((Closeable)httpclient).close();
}
}
InternalCallVerifier EqualityVerifier
@Test public void testNonSimpleActualRequest() throws Exception {
configureAllowOrigins(true,null);
String r=configClient.replacePath("/setAllowCredentials/false").accept("text/plain").post(null,String.class);
assertEquals("ok",r);
HttpClient httpclient=HttpClientBuilder.create().build();
HttpDelete httpdelete=new HttpDelete("http://localhost:" + PORT + "/untest/delete");
httpdelete.addHeader("Origin","http://localhost:" + PORT);
HttpResponse response=httpclient.execute(httpdelete);
assertEquals(200,response.getStatusLine().getStatusCode());
assertAllowCredentials(response,false);
assertOriginResponse(true,null,true,response);
if (httpclient instanceof Closeable) {
((Closeable)httpclient).close();
}
}
InternalCallVerifier EqualityVerifier
@Test public void testAllowCredentials() throws Exception {
String r=configClient.replacePath("/setAllowCredentials/true").accept("text/plain").post(null,String.class);
assertEquals("ok",r);
HttpClient httpclient=HttpClientBuilder.create().build();
HttpGet httpget=new HttpGet("http://localhost:" + PORT + "/untest/simpleGet/HelloThere");
httpget.addHeader("Origin","http://localhost:" + PORT);
HttpResponse response=httpclient.execute(httpget);
assertEquals(200,response.getStatusLine().getStatusCode());
assertAllowCredentials(response,true);
if (httpclient instanceof Closeable) {
((Closeable)httpclient).close();
}
}
InternalCallVerifier EqualityVerifier
@Test public void preflightPostClassAnnotationFail() throws ClientProtocolException, IOException {
HttpClient httpclient=HttpClientBuilder.create().build();
HttpOptions httpoptions=new HttpOptions("http://localhost:" + PORT + "/antest/unannotatedPost");
httpoptions.addHeader("Origin","http://in.org");
httpoptions.addHeader("Content-Type","application/json");
httpoptions.addHeader(CorsHeaderConstants.HEADER_AC_REQUEST_METHOD,"POST");
httpoptions.addHeader(CorsHeaderConstants.HEADER_AC_REQUEST_HEADERS,"X-custom-1");
HttpResponse response=httpclient.execute(httpoptions);
assertEquals(200,response.getStatusLine().getStatusCode());
assertEquals(0,response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_ORIGIN).length);
assertEquals(0,response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_HEADERS).length);
assertEquals(0,response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_METHODS).length);
if (httpclient instanceof Closeable) {
((Closeable)httpclient).close();
}
}
InternalCallVerifier EqualityVerifier
@Test public void testForbidCredentials() throws Exception {
String r=configClient.replacePath("/setAllowCredentials/false").accept("text/plain").post(null,String.class);
assertEquals("ok",r);
HttpClient httpclient=HttpClientBuilder.create().build();
HttpGet httpget=new HttpGet("http://localhost:" + PORT + "/untest/simpleGet/HelloThere");
httpget.addHeader("Origin","http://localhost:" + PORT);
HttpResponse response=httpclient.execute(httpget);
assertEquals(200,response.getStatusLine().getStatusCode());
assertAllowCredentials(response,false);
if (httpclient instanceof Closeable) {
((Closeable)httpclient).close();
}
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void preflightPostClassAnnotationPass2() throws ClientProtocolException, IOException {
HttpClient httpclient=HttpClientBuilder.create().build();
HttpOptions httpoptions=new HttpOptions("http://localhost:" + PORT + "/antest/unannotatedPost");
httpoptions.addHeader("Origin","http://area51.mil:31415");
httpoptions.addHeader("Content-Type","application/json");
httpoptions.addHeader(CorsHeaderConstants.HEADER_AC_REQUEST_METHOD,"POST");
httpoptions.addHeader(CorsHeaderConstants.HEADER_AC_REQUEST_HEADERS,"X-custom-1, X-custom-2");
HttpResponse response=httpclient.execute(httpoptions);
assertEquals(200,response.getStatusLine().getStatusCode());
Header[] origin=response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_ORIGIN);
assertEquals(1,origin.length);
assertEquals("http://area51.mil:31415",origin[0].getValue());
Header[] method=response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_METHODS);
assertEquals(1,method.length);
assertEquals("POST",method[0].getValue());
Header[] requestHeaders=response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_HEADERS);
assertEquals(1,requestHeaders.length);
assertTrue(requestHeaders[0].getValue().contains("X-custom-1"));
assertTrue(requestHeaders[0].getValue().contains("X-custom-2"));
if (httpclient instanceof Closeable) {
((Closeable)httpclient).close();
}
}
InternalCallVerifier EqualityVerifier
@Test public void preflightPostClassAnnotationFail2() throws ClientProtocolException, IOException {
HttpClient httpclient=HttpClientBuilder.create().build();
HttpOptions httpoptions=new HttpOptions("http://localhost:" + PORT + "/antest/unannotatedPost");
httpoptions.addHeader("Origin","http://area51.mil:31415");
httpoptions.addHeader("Content-Type","application/json");
httpoptions.addHeader(CorsHeaderConstants.HEADER_AC_REQUEST_METHOD,"POST");
httpoptions.addHeader(CorsHeaderConstants.HEADER_AC_REQUEST_HEADERS,"X-custom-3");
HttpResponse response=httpclient.execute(httpoptions);
assertEquals(200,response.getStatusLine().getStatusCode());
assertEquals(0,response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_ORIGIN).length);
assertEquals(0,response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_HEADERS).length);
assertEquals(0,response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_METHODS).length);
if (httpclient instanceof Closeable) {
((Closeable)httpclient).close();
}
}
InternalCallVerifier EqualityVerifier
@Test public void simplePostClassAnnotation() throws ClientProtocolException, IOException {
HttpClient httpclient=HttpClientBuilder.create().build();
HttpOptions httpoptions=new HttpOptions("http://localhost:" + PORT + "/antest/unannotatedPost");
httpoptions.addHeader("Origin","http://in.org");
httpoptions.addHeader("Content-Type","text/plain");
httpoptions.addHeader(CorsHeaderConstants.HEADER_AC_REQUEST_METHOD,"POST");
HttpResponse response=httpclient.execute(httpoptions);
assertEquals(200,response.getStatusLine().getStatusCode());
if (httpclient instanceof Closeable) {
((Closeable)httpclient).close();
}
}
InternalCallVerifier EqualityVerifier
@Test public void testAnnotatedClassWrongOrigin() throws Exception {
HttpClient httpclient=HttpClientBuilder.create().build();
HttpGet httpget=new HttpGet("http://localhost:" + PORT + "/antest/simpleGet/HelloThere");
httpget.addHeader("Origin","http://su.us:1001");
HttpResponse response=httpclient.execute(httpget);
assertEquals(200,response.getStatusLine().getStatusCode());
HttpEntity entity=response.getEntity();
String e=IOUtils.toString(entity.getContent(),"utf-8");
assertEquals("HelloThere",e);
assertOriginResponse(false,null,false,response);
if (httpclient instanceof Closeable) {
((Closeable)httpclient).close();
}
}
Class: org.apache.cxf.systest.jaxrs.description.AbstractSwagger2ServiceDescriptionTest InternalCallVerifier EqualityVerifier
@Test public void testApiListingIsProperlyReturnedYAML() throws Exception {
final WebClient client=createWebClient("/swagger.yaml");
try {
final Response r=client.get();
assertEquals(Status.OK.getStatusCode(),r.getStatus());
Yaml yaml=new Yaml();
assertEquals(yaml.load(getExpectedValue(getExpectedFileYaml(),getPort())).toString(),yaml.load(IOUtils.readStringFromStream((InputStream)r.getEntity())).toString());
}
finally {
client.close();
}
}
InternalCallVerifier EqualityVerifier
@Test public void testApiListingIsProperlyReturnedJSON() throws Exception {
final WebClient client=createWebClient("/swagger.json");
try {
final Response r=client.get();
assertEquals(Status.OK.getStatusCode(),r.getStatus());
JSONAssert.assertEquals(getExpectedValue(getExpectedFileJson(),getPort()),IOUtils.readStringFromStream((InputStream)r.getEntity()),false);
}
finally {
client.close();
}
}
Class: org.apache.cxf.systest.jaxrs.description.AbstractSwaggerServiceDescriptionTest InternalCallVerifier EqualityVerifier
@Test public void testApiListingIsProperlyReturned() throws Exception {
final WebClient client=createWebClient("/api-docs");
try {
final Response r=client.get();
assertEquals(Status.OK.getStatusCode(),r.getStatus());
JSONAssert.assertEquals(Json.createObjectBuilder().add("apiVersion","1.0.0").add("swaggerVersion","1.2").add("apis",Json.createArrayBuilder().add(Json.createObjectBuilder().add("path","/bookstore").add("description","Sample JAX-RS service with Swagger documentation"))).add("info",Json.createObjectBuilder().add("title","Sample REST Application").add("description","The Application").add("contact","users@cxf.apache.org").add("license","Apache 2.0 License").add("licenseUrl","http://www.apache.org/licenses/LICENSE-2.0.html")).build().toString(),IOUtils.readStringFromStream((InputStream)r.getEntity()),false);
}
finally {
client.close();
}
}
InternalCallVerifier EqualityVerifier
@Test public void testApiResourcesAreProperlyReturned() throws Exception {
final WebClient client=createWebClient("/api-docs/bookstore");
try {
final Response r=client.get();
assertEquals(Status.OK.getStatusCode(),r.getStatus());
JSONAssert.assertEquals(Json.createObjectBuilder().add("apiVersion","1.0.0").add("swaggerVersion","1.2").add("basePath","http://localhost:" + getPort() + "/").add("resourcePath","/bookstore").add("apis",Json.createArrayBuilder().add(Json.createObjectBuilder().add("path","/bookstore/{id}").add("operations",Json.createArrayBuilder().add(DELETE_METHOD_SPEC).add(GET_BY_ID_METHOD_SPEC))).add(Json.createObjectBuilder().add("path","/bookstore").add("operations",Json.createArrayBuilder().add(GET_METHOD_SPEC)))).add("models",BOOK_MODEL_SPEC).build().toString(),IOUtils.readStringFromStream((InputStream)r.getEntity()),false);
}
finally {
client.close();
}
}
Class: org.apache.cxf.systest.jaxrs.discovery.JAXRSServerSpringDiscoveryTest InternalCallVerifier EqualityVerifier
@Test public void testThatClientDiscoversServiceProperly() throws Exception {
BookStore bs=JAXRSClientFactory.create("http://localhost:" + PORT,BookStore.class,"org/apache/cxf/systest/jaxrs/discovery/jaxrs-http-client.xml");
assertEquals("http://localhost:" + PORT,WebClient.client(bs).getBaseURI().toString());
BookWithValidation book=bs.getBook("123");
assertEquals(book.getId(),"123");
}
Class: org.apache.cxf.systest.jaxrs.failover.AbstractFailoverTest UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testSequentialStrategyWithRetries() throws Exception {
String address="http://localhost:" + NON_PORT + "/non-existent";
String address2="http://localhost:" + NON_PORT + "/non-existent2";
FailoverFeature feature=new FailoverFeature();
List alternateAddresses=new ArrayList();
alternateAddresses.add(address);
alternateAddresses.add(address2);
CustomRetryStrategy strategy=new CustomRetryStrategy();
strategy.setMaxNumberOfRetries(5);
strategy.setAlternateAddresses(alternateAddresses);
feature.setStrategy(strategy);
BookStore store=getBookStore(address,feature);
try {
store.getBook("1");
fail("Exception expected");
}
catch ( ProcessingException ex) {
assertEquals(10,strategy.getTotalCount());
assertEquals(5,strategy.getAddressCount(address));
assertEquals(5,strategy.getAddressCount(address2));
}
}
Class: org.apache.cxf.systest.jaxrs.failover.LoadDistributorTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testSingleAltAddress() throws Exception {
LoadDistributorFeature feature=new LoadDistributorFeature();
List alternateAddresses=new ArrayList();
alternateAddresses.add(Server.ADDRESS2);
SequentialStrategy strategy=new SequentialStrategy();
strategy.setAlternateAddresses(alternateAddresses);
feature.setStrategy(strategy);
BookStore bookStore=getBookStore(Server.ADDRESS1,feature);
Book book=bookStore.getBook("123");
assertEquals("unexpected id",123L,book.getId());
book=bookStore.getBook("123");
assertEquals("unexpected id",123L,book.getId());
}
Class: org.apache.cxf.systest.jaxrs.jms.JAXRSJmsTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookFromWebClientWithPath() throws Exception {
String endpointAddressUrlEncoded="jms:jndi:dynamicQueues/test.jmstransport.text" + "?jndiInitialContextFactory=org.apache.activemq.jndi.ActiveMQInitialContextFactory" + "&replyToName=dynamicQueues/test.jmstransport.response"+ "&jndiURL=tcp://localhost:" + JMS_PORT + "&jndiConnectionFactoryName=ConnectionFactory";
WebClient client=WebClient.create(endpointAddressUrlEncoded);
client.path("bookstore").path("books").path("123");
Book book=client.get(Book.class);
assertEquals("Get a wrong response code.",200,client.getResponse().getStatus());
assertEquals("Get a wrong book id.",123,book.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookFromProxyClientWithQuery() throws Exception {
String endpointAddressUrlEncoded="jms:jndi:dynamicQueues/test.jmstransport.text" + "?jndiInitialContextFactory=org.apache.activemq.jndi.ActiveMQInitialContextFactory" + "&replyToName=dynamicQueues/test.jmstransport.response"+ "&jndiURL=tcp://localhost:" + JMS_PORT + "&jndiConnectionFactoryName=ConnectionFactory";
JMSBookStore client=JAXRSClientFactory.create(endpointAddressUrlEncoded,JMSBookStore.class);
Book book=client.getBookByURLQuery(new String[]{"1","2","3"});
assertEquals("Get a wrong response code.",200,WebClient.client(client).getResponse().getStatus());
assertEquals("Get a wrong book id.",123,book.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookFromProxyClient() throws Exception {
String endpointAddressUrlEncoded="jms:jndi:dynamicQueues/test.jmstransport.text" + "?jndiInitialContextFactory=org.apache.activemq.jndi.ActiveMQInitialContextFactory" + "&replyToName=dynamicQueues/test.jmstransport.response"+ "&jndiURL=tcp://localhost:" + JMS_PORT + "&jndiConnectionFactoryName=ConnectionFactory";
JMSBookStore client=JAXRSClientFactory.create(endpointAddressUrlEncoded,JMSBookStore.class);
Book book=client.getBook("123");
assertEquals("Get a wrong response code.",200,WebClient.client(client).getResponse().getStatus());
assertEquals("Get a wrong book id.",123,book.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookFromSubresourceProxyClient() throws Exception {
String endpointAddressUrlEncoded="jms:jndi:dynamicQueues/test.jmstransport.text" + "?jndiInitialContextFactory=org.apache.activemq.jndi.ActiveMQInitialContextFactory" + "&replyToName=dynamicQueues/test.jmstransport.response"+ "&jndiURL=tcp://localhost:" + JMS_PORT + "&jndiConnectionFactoryName=ConnectionFactory";
JMSBookStore client=JAXRSClientFactory.create(endpointAddressUrlEncoded,JMSBookStore.class);
Book bookProxy=client.getBookSubResource("123");
Book book=bookProxy.retrieveState();
assertEquals("Get a wrong response code.",200,WebClient.client(bookProxy).getResponse().getStatus());
assertEquals("Get a wrong book id.",123,book.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookFromWebClient() throws Exception {
String endpointAddressUrlEncoded="jms:jndi:dynamicQueues/test.jmstransport.text" + "?replyToName=dynamicQueues/test.jmstransport.response" + "&jndiInitialContextFactory=org.apache.activemq.jndi.ActiveMQInitialContextFactory"+ "&jndiURL=tcp://localhost:"+ JMS_PORT;
WebClient client=WebClient.create(endpointAddressUrlEncoded);
WebClient.getConfig(client).getRequestContext().put(org.apache.cxf.message.Message.REQUEST_URI,"/bookstore/books/123");
Book book=client.get(Book.class);
assertEquals("Get a wrong response code.",200,client.getResponse().getStatus());
assertEquals("Get a wrong book id.",123,book.getId());
}
Class: org.apache.cxf.systest.jaxrs.provider.JsrJsonpProviderTest InternalCallVerifier EqualityVerifier ConditionMatcher HybridVerifier
@Test public void testPostAndGetComplexJsonObject(){
testPostComplexJsonObject();
final Response r=createWebClient("/bookstore/books/1").get();
assertEquals(Status.OK.getStatusCode(),r.getStatus());
JsonObject obj=r.readEntity(JsonObject.class);
assertThat(obj.getInt("id"),equalTo(1));
assertThat(obj.getString("name"),equalTo("Book 1"));
assertThat(obj.get("chapters"),instanceOf(JsonArray.class));
final JsonArray chapters=(JsonArray)obj.get("chapters");
assertThat(chapters.size(),equalTo(2));
assertThat(((JsonObject)chapters.get(0)).getInt("id"),equalTo(1));
assertThat(((JsonObject)chapters.get(0)).getString("title"),equalTo("Chapter 1"));
assertThat(((JsonObject)chapters.get(1)).getInt("id"),equalTo(2));
assertThat(((JsonObject)chapters.get(1)).getString("title"),equalTo("Chapter 2"));
}
InternalCallVerifier EqualityVerifier ConditionMatcher HybridVerifier
@Test public void testPostAndGetBooks(){
testPostSimpleJsonObject();
final Response r=createWebClient("/bookstore/books").get();
assertEquals(Status.OK.getStatusCode(),r.getStatus());
final JsonArray obj=r.readEntity(JsonArray.class);
assertThat(obj.size(),equalTo(1));
assertThat(obj.get(0),instanceOf(JsonObject.class));
assertThat(((JsonObject)obj.get(0)).getInt("id"),equalTo(1));
assertThat(((JsonObject)obj.get(0)).getString("name"),equalTo("Book 1"));
}
InternalCallVerifier EqualityVerifier ConditionMatcher HybridVerifier
@Test public void testPostAndGetSimpleJsonObject(){
testPostSimpleJsonObject();
final Response r=createWebClient("/bookstore/books/1").get();
assertEquals(Status.OK.getStatusCode(),r.getStatus());
JsonObject obj=r.readEntity(JsonObject.class);
assertThat(obj.getInt("id"),equalTo(1));
assertThat(obj.getString("name"),equalTo("Book 1"));
assertThat(obj.get("chapters"),nullValue());
}
Class: org.apache.cxf.systest.jaxrs.security.JAXRS20HttpsBookTest InternalCallVerifier EqualityVerifier
@Test public void testGetBook() throws Exception {
ClientBuilder builder=ClientBuilder.newBuilder();
KeyStore trustStore=loadStore("src/test/java/org/apache/cxf/systest/http/resources/Truststore.jks","password");
builder.trustStore(trustStore);
builder.hostnameVerifier(new AllowAllHostnameVerifier());
KeyStore keyStore=loadStore("src/test/java/org/apache/cxf/systest/http/resources/Morpit.jks","password");
builder.keyStore(keyStore,"password");
Client client=builder.build();
client.register(new LoggingFeature());
WebTarget target=client.target("https://localhost:" + PORT + "/bookstore/securebooks/123");
Book b=target.request().accept(MediaType.APPLICATION_XML_TYPE).get(Book.class);
assertEquals(123,b.getId());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetBookSslContext() throws Exception {
ClientBuilder builder=ClientBuilder.newBuilder();
SSLContext sslContext=createSSLContext();
builder.sslContext(sslContext);
builder.hostnameVerifier(new AllowAllHostnameVerifier());
Client client=builder.build();
WebTarget target=client.target("https://localhost:" + PORT + "/bookstore/securebooks/123");
Book b=target.request().accept(MediaType.APPLICATION_XML_TYPE).get(Book.class);
assertEquals(123,b.getId());
}
Class: org.apache.cxf.systest.jaxrs.security.JAXRSHttpsBookTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBook123ProxyToWebClient() throws Exception {
BookStore bs=JAXRSClientFactory.create("https://localhost:" + PORT,BookStore.class,CLIENT_CONFIG_FILE1);
Book b=bs.getSecureBook("123");
assertEquals(b.getId(),123);
WebClient wc=WebClient.fromClient(WebClient.client(bs));
wc.path("/bookstore/securebooks/123").accept(MediaType.APPLICATION_XML_TYPE);
Book b2=wc.get(Book.class);
assertEquals(123,b2.getId());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetBook123WebClientFromSpringWildcard() throws Exception {
ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext(new String[]{CLIENT_CONFIG_FILE5});
Object bean=ctx.getBean("bookService.proxyFactory");
assertNotNull(bean);
JAXRSClientFactoryBean cfb=(JAXRSClientFactoryBean)bean;
WebClient wc=(WebClient)cfb.create();
assertEquals("https://localhost:" + PORT,wc.getBaseURI().toString());
wc.accept("application/xml");
wc.path("bookstore/securebooks/123");
TheBook b=wc.get(TheBook.class);
assertEquals(b.getId(),123);
b=wc.get(TheBook.class);
assertEquals(b.getId(),123);
ctx.close();
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetBook123ProxyFromSpringWildcard() throws Exception {
ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext(new String[]{CLIENT_CONFIG_FILE4});
Object bean=ctx.getBean("bookService.proxyFactory");
assertNotNull(bean);
JAXRSClientFactoryBean cfb=(JAXRSClientFactoryBean)bean;
BookStore bs=cfb.create(BookStore.class);
assertEquals("https://localhost:" + PORT,WebClient.client(bs).getBaseURI().toString());
WebClient wc=WebClient.fromClient(WebClient.client(bs));
assertEquals("https://localhost:" + PORT,WebClient.client(bs).getBaseURI().toString());
wc.accept("application/xml");
wc.path("bookstore/securebooks/123");
TheBook b=wc.get(TheBook.class);
assertEquals(b.getId(),123);
b=wc.get(TheBook.class);
assertEquals(b.getId(),123);
ctx.close();
}
InternalCallVerifier EqualityVerifier NullVerifier IgnoredMethod HybridVerifier
@Test @Ignore("Works in the studio only if local jaxrs.xsd is updated to have jaxrs:client") public void testGetBook123WebClientFromSpringWildcardOldJaxrsClient() throws Exception {
ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext(new String[]{CLIENT_CONFIG_FILE_OLD});
Object bean=ctx.getBean("bookService.proxyFactory");
assertNotNull(bean);
JAXRSClientFactoryBean cfb=(JAXRSClientFactoryBean)bean;
WebClient wc=(WebClient)cfb.create();
assertEquals("https://localhost:" + PORT,wc.getBaseURI().toString());
wc.accept("application/xml");
wc.path("bookstore/securebooks/123");
TheBook b=wc.get(TheBook.class);
assertEquals(b.getId(),123);
b=wc.get(TheBook.class);
assertEquals(b.getId(),123);
ctx.close();
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBook123WebClientToProxy() throws Exception {
WebClient wc=WebClient.create("https://localhost:" + PORT,CLIENT_CONFIG_FILE1);
wc.path("/bookstore/securebooks/123").accept(MediaType.APPLICATION_XML_TYPE);
Book b=wc.get(Book.class);
assertEquals(123,b.getId());
wc.back(true);
BookStore bs=JAXRSClientFactory.fromClient(wc,BookStore.class);
Book b2=bs.getSecureBook("123");
assertEquals(b2.getId(),123);
}
Class: org.apache.cxf.systest.jaxrs.security.JAXRSJaasConfigurationSecurityTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testJaasFilterAuthenticationFailure() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/service/jaasConfigFilter/bookstorestorage/thosebooks/123";
WebClient wc=WebClient.create(endpointAddress);
wc.accept("text/xml");
wc.header(HttpHeaders.AUTHORIZATION,"Basic " + base64Encode("foo" + ":" + "bar1"));
Response r=wc.get();
assertEquals(401,r.getStatus());
Object wwwAuthHeader=r.getMetadata().getFirst(HttpHeaders.WWW_AUTHENTICATE);
assertNotNull(wwwAuthHeader);
assertEquals("Basic",wwwAuthHeader.toString());
}
Class: org.apache.cxf.systest.jaxrs.security.JAXRSJaasSecurityTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testJaasFilterAuthenticationFailure() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/service/jaas2/bookstorestorage/thosebooks/123";
WebClient wc=WebClient.create(endpointAddress);
AuthorizationPolicy pol=new AuthorizationPolicy();
pol.setUserName("foo");
pol.setPassword("bar1");
WebClient.getConfig(wc).getHttpConduit().setAuthorization(pol);
wc.accept("application/xml");
Response r=wc.get();
assertEquals(401,r.getStatus());
Object wwwAuthHeader=r.getMetadata().getFirst(HttpHeaders.WWW_AUTHENTICATE);
assertNotNull(wwwAuthHeader);
assertEquals("Basic",wwwAuthHeader.toString());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testJaasFilterWebClientAuthorizationPolicy() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/service/jaas2/bookstorestorage/thosebooks/123";
WebClient wc=WebClient.create(endpointAddress);
AuthorizationPolicy pol=new AuthorizationPolicy();
pol.setUserName("bob");
pol.setPassword("bobspassword");
WebClient.getConfig(wc).getHttpConduit().setAuthorization(pol);
wc.accept("application/xml");
Book book=wc.get(Book.class);
assertEquals(123L,book.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testJaasFilterProxyAuthorizationPolicy() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/service/jaas2";
SecureBookStoreNoAnnotations proxy=JAXRSClientFactory.create(endpointAddress,SecureBookStoreNoAnnotations.class,"bob","bobspassword",null);
Book book=proxy.getThatBook(123L);
assertEquals(123L,book.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testJaasFilterWebClientAuthorizationPolicy2() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/service/jaas2/bookstorestorage/thosebooks/123";
WebClient wc=WebClient.create(endpointAddress,"bob","bobspassword",null);
wc.accept("application/xml");
Book book=wc.get(Book.class);
assertEquals(123L,book.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testJaasFilterAuthenticationFailureWithRedirection() throws Exception {
String endpointAddress="http://localhost:" + PORT + "/service/jaas2/bookstorestorage/thosebooks/123";
WebClient wc=WebClient.create(endpointAddress);
wc.accept("text/xml,text/html");
wc.header(HttpHeaders.AUTHORIZATION,"Basic " + base64Encode("foo" + ":" + "bar1"));
Response r=wc.get();
assertEquals(307,r.getStatus());
Object locationHeader=r.getMetadata().getFirst(HttpHeaders.LOCATION);
assertNotNull(locationHeader);
assertEquals("http://localhost:" + PORT + "/login.jsp",locationHeader.toString());
}
Class: org.apache.cxf.systest.jaxrs.security.JAXRSSpringSecurityClassTest InternalCallVerifier EqualityVerifier
@Test public void testBookFromForm() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + PORT + "/bookstorestorage/bookforms","foo","bar",null);
wc.accept("application/xml");
Response r=wc.form(new Form().param("name","CXF Rocks").param("id","123"));
Book b=readBook((InputStream)r.getEntity());
assertEquals("CXF Rocks",b.getName());
assertEquals(123L,b.getId());
}
InternalCallVerifier EqualityVerifier IgnoredMethod HybridVerifier
@Test @Ignore("Spring Security 3 does not preserve POSTed form parameters as HTTPServletRequest parameters") public void testBookFromHttpRequestParameters() throws Exception {
WebClient wc=WebClient.create("http://localhost:" + PORT + "/bookstorestorage/bookforms2","foo","bar",null);
WebClient.getConfig(wc).getHttpConduit().getClient().setReceiveTimeout(100000000L);
wc.accept("application/xml");
Response r=wc.form(new Form().param("name","CXF Rocks").param("id","123"));
Book b=readBook((InputStream)r.getEntity());
assertEquals("CXF Rocks",b.getName());
assertEquals(123L,b.getId());
}
Class: org.apache.cxf.systest.jaxrs.security.jose.jwejws.JAXRSJweJwsTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testJweRsaJwsRsaCertInHeaders() throws Exception {
String address="https://localhost:" + PORT + "/jwejwsrsaCertInHeaders";
BookStore bs=createJweJwsBookStore(address,null,null);
WebClient.getConfig(bs).getRequestContext().put("rs.security.signature.include.cert","true");
WebClient.getConfig(bs).getRequestContext().put("rs.security.encryption.include.cert","true");
String text=bs.echoText("book");
assertEquals("book",text);
}
InternalCallVerifier EqualityVerifier
@Test public void testJwsJwkEC() throws Exception {
String address="https://localhost:" + PORT + "/jwsjwkec";
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
SpringBusFactory bf=new SpringBusFactory();
URL busFile=JAXRSJweJwsTest.class.getResource("client.xml");
Bus springBus=bf.createBus(busFile.toString());
bean.setBus(springBus);
bean.setServiceClass(BookStore.class);
bean.setAddress(address);
List providers=new LinkedList();
JwsWriterInterceptor jwsWriter=new JwsWriterInterceptor();
jwsWriter.setUseJwsOutputStream(true);
providers.add(jwsWriter);
providers.add(new JwsClientResponseFilter());
bean.setProviders(providers);
bean.getProperties(true).put("rs.security.signature.out.properties","org/apache/cxf/systest/jaxrs/security/jws.ec.private.properties");
bean.getProperties(true).put("rs.security.signature.in.properties","org/apache/cxf/systest/jaxrs/security/jws.ec.public.properties");
BookStore bs=bean.create(BookStore.class);
String text=bs.echoText("book");
assertEquals("book",text);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testJwsJwkPlainTextHMac() throws Exception {
String address="https://localhost:" + PORT + "/jwsjwkhmac";
BookStore bs=createJwsBookStore(address,null);
String text=bs.echoText("book");
assertEquals("book",text);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testJwsJwkBookHMac() throws Exception {
String address="https://localhost:" + PORT + "/jwsjwkhmac";
BookStore bs=createJwsBookStore(address,Collections.singletonList(new JacksonJsonProvider()));
Book book=bs.echoBook(new Book("book",123L));
assertEquals("book",book.getName());
assertEquals(123L,book.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testJweRsaJwsRsaXML() throws Exception {
String address="https://localhost:" + PORT + "/jwejwsrsa";
BookStore bs=createJweJwsBookStore(address,null,null);
Book book=new Book();
book.setName("book");
book=bs.echoBook2(book);
assertEquals("book",book.getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testJweJwkBookBeanRSA() throws Exception {
String address="https://localhost:" + PORT + "/jwejwkrsa";
BookStore bs=createJweBookStore(address,Collections.singletonList(new JacksonJsonProvider()));
Book book=bs.echoBook(new Book("book",123L));
assertEquals("book",book.getName());
assertEquals(123L,book.getId());
}
InternalCallVerifier EqualityVerifier
@Test public void testJweJwkAesWrap() throws Exception {
String address="https://localhost:" + PORT + "/jwejwkaeswrap";
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
SpringBusFactory bf=new SpringBusFactory();
URL busFile=JAXRSJweJwsTest.class.getResource("client.xml");
Bus springBus=bf.createBus(busFile.toString());
bean.setBus(springBus);
bean.setServiceClass(BookStore.class);
bean.setAddress(address);
List providers=new LinkedList();
JweWriterInterceptor jweWriter=new JweWriterInterceptor();
jweWriter.setUseJweOutputStream(true);
providers.add(jweWriter);
providers.add(new JweClientResponseFilter());
bean.setProviders(providers);
bean.getProperties(true).put("rs.security.encryption.properties","org/apache/cxf/systest/jaxrs/security/secret.jwk.properties");
bean.getProperties(true).put("jose.debug",true);
BookStore bs=bean.create(BookStore.class);
String text=bs.echoText("book");
assertEquals("book",text);
}
InternalCallVerifier EqualityVerifier
@Test public void testJweAesCbcHmac() throws Exception {
String address="https://localhost:" + PORT + "/jweaescbchmac";
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
SpringBusFactory bf=new SpringBusFactory();
URL busFile=JAXRSJweJwsTest.class.getResource("client.xml");
Bus springBus=bf.createBus(busFile.toString());
bean.setBus(springBus);
bean.setServiceClass(BookStore.class);
bean.setAddress(address);
List providers=new LinkedList();
JweWriterInterceptor jweWriter=new JweWriterInterceptor();
jweWriter.setUseJweOutputStream(true);
final String cekEncryptionKey="GawgguFyGrWKav7AX4VKUg";
AesWrapKeyEncryptionAlgorithm keyEncryption=new AesWrapKeyEncryptionAlgorithm(cekEncryptionKey,KeyAlgorithm.A128KW);
jweWriter.setEncryptionProvider(new AesCbcHmacJweEncryption(ContentAlgorithm.A128CBC_HS256,keyEncryption));
JweClientResponseFilter jweReader=new JweClientResponseFilter();
jweReader.setDecryptionProvider(new AesCbcHmacJweDecryption(new AesWrapKeyDecryptionAlgorithm(cekEncryptionKey)));
providers.add(jweWriter);
providers.add(jweReader);
bean.setProviders(providers);
BookStore bs=bean.create(BookStore.class);
String text=bs.echoText("book");
assertEquals("book",text);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testJweRsaJwsBookHMac() throws Exception {
String address="https://localhost:" + PORT + "/jwejwshmac";
HmacJwsSignatureProvider hmacProvider=new HmacJwsSignatureProvider(ENCODED_MAC_KEY,SignatureAlgorithm.HS256);
BookStore bs=createJweJwsBookStore(address,hmacProvider,Collections.singletonList(new JacksonJsonProvider()));
Book book=bs.echoBook(new Book("book",123L));
assertEquals("book",book.getName());
assertEquals(123L,book.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testJweJwkPlainTextRSA() throws Exception {
String address="https://localhost:" + PORT + "/jwejwkrsa";
BookStore bs=createJweBookStore(address,null);
String text=bs.echoText("book");
assertEquals("book",text);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testJweRsaJwsPlainTextHMac() throws Exception {
String address="https://localhost:" + PORT + "/jwejwshmac";
HmacJwsSignatureProvider hmacProvider=new HmacJwsSignatureProvider(ENCODED_MAC_KEY,SignatureAlgorithm.HS256);
BookStore bs=createJweJwsBookStore(address,hmacProvider,null);
String text=bs.echoText("book");
assertEquals("book",text);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testJweRsaJwsRsa() throws Exception {
String address="https://localhost:" + PORT + "/jwejwsrsa";
BookStore bs=createJweJwsBookStore(address,null,null);
String text=bs.echoText("book");
assertEquals("book",text);
}
InternalCallVerifier EqualityVerifier
@Test public void testJweRsaJwsRsaCert() throws Exception {
String address="https://localhost:" + PORT + "/jwejwsrsacert";
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
SpringBusFactory bf=new SpringBusFactory();
URL busFile=JAXRSJweJwsTest.class.getResource("client.xml");
Bus springBus=bf.createBus(busFile.toString());
bean.setBus(springBus);
bean.setServiceClass(BookStore.class);
bean.setAddress(address);
List providers=new LinkedList();
JweWriterInterceptor jweWriter=new JweWriterInterceptor();
jweWriter.setUseJweOutputStream(true);
providers.add(jweWriter);
providers.add(new JweClientResponseFilter());
JwsWriterInterceptor jwsWriter=new JwsWriterInterceptor();
jwsWriter.setUseJwsOutputStream(true);
providers.add(jwsWriter);
providers.add(new JwsClientResponseFilter());
bean.setProviders(providers);
bean.getProperties(true).put("rs.security.keystore.file","org/apache/cxf/systest/jaxrs/security/certs/jwkPublicSet.txt");
bean.getProperties(true).put("rs.security.signature.out.properties",CLIENT_JWEJWS_PROPERTIES);
bean.getProperties(true).put("rs.security.encryption.in.properties",CLIENT_JWEJWS_PROPERTIES);
PrivateKeyPasswordProvider provider=new PrivateKeyPasswordProviderImpl();
bean.getProperties(true).put("rs.security.signature.key.password.provider",provider);
bean.getProperties(true).put("rs.security.decryption.key.password.provider",provider);
BookStore bs=bean.create(BookStore.class);
WebClient.getConfig(bs).getRequestContext().put("rs.security.keystore.alias.jwe.out","AliceCert");
WebClient.getConfig(bs).getRequestContext().put("rs.security.keystore.alias.jws.in","AliceCert");
String text=bs.echoText("book");
assertEquals("book",text);
}
Class: org.apache.cxf.systest.jaxrs.security.jose.jwejws.JAXRSJwsJsonTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testJweCompactJwsJsonBookBeanHmac() throws Exception {
if (!SecurityTestUtil.checkUnrestrictedPoliciesInstalled()) {
return;
}
String address="https://localhost:" + PORT + "/jwejwsjsonhmac";
List> extraProviders=Arrays.asList(new JacksonJsonProvider(),new JweWriterInterceptor(),new JweClientResponseFilter());
String jwkStoreProperty="org/apache/cxf/systest/jaxrs/security/secret.jwk.properties";
Map props=new HashMap();
props.put("rs.security.signature.list.properties",jwkStoreProperty);
props.put("rs.security.encryption.properties",jwkStoreProperty);
BookStore bs=createBookStore(address,props,extraProviders);
Book book=bs.echoBook(new Book("book",123L));
assertEquals("book",book.getName());
assertEquals(123L,book.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testJwsJsonBookBeanHmac() throws Exception {
String address="https://localhost:" + PORT + "/jwsjsonhmac";
BookStore bs=createBookStore(address,"org/apache/cxf/systest/jaxrs/security/secret.jwk.properties",Collections.singletonList(new JacksonJsonProvider()));
Book book=bs.echoBook(new Book("book",123L));
assertEquals("book",book.getName());
assertEquals(123L,book.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testJwsJsonPlainTextHmacXML() throws Exception {
String address="https://localhost:" + PORT + "/jwsjsonhmac";
BookStore bs=createBookStore(address,"org/apache/cxf/systest/jaxrs/security/secret.jwk.properties",null);
String text=bs.echoText("book");
assertEquals("book",text);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testJwsJsonBookDoubleHmacSinglePropsFile() throws Exception {
String address="https://localhost:" + PORT + "/jwsjsonhmac2";
List properties=new ArrayList();
properties.add("org/apache/cxf/systest/jaxrs/security/secret.jwk.hmac2.properties");
BookStore bs=createBookStore(address,properties,null);
Book book=bs.echoBook2(new Book("book",123L));
assertEquals("book",book.getName());
assertEquals(123L,book.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testJwsJsonPlainTextHmac() throws Exception {
String address="https://localhost:" + PORT + "/jwsjsonhmac";
BookStore bs=createBookStore(address,"org/apache/cxf/systest/jaxrs/security/secret.jwk.properties",null);
String text=bs.echoText("book");
assertEquals("book",text);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testJwsJsonBookDoubleHmac() throws Exception {
String address="https://localhost:" + PORT + "/jwsjsonhmac2";
List properties=new ArrayList();
properties.add("org/apache/cxf/systest/jaxrs/security/secret.jwk.properties");
properties.add("org/apache/cxf/systest/jaxrs/security/secret.jwk.hmac.properties");
BookStore bs=createBookStore(address,properties,null);
Book book=bs.echoBook(new Book("book",123L));
assertEquals("book",book.getName());
assertEquals(123L,book.getId());
}
Class: org.apache.cxf.systest.jaxrs.security.oauth.TemporaryCredentialServiceTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetTemporaryCredentialsURIQuery() throws Exception {
Map parameters=new HashMap();
parameters.put(OAuth.OAUTH_CALLBACK,OAuthTestUtils.CALLBACK);
for ( ParameterStyle style : ParameterStyle.values()) {
for ( String signMethod : OAuthTestUtils.SIGN_METHOD) {
LOG.log(Level.INFO,"Preparing request with parameter style: {0} and signature method: {1}",new String[]{style.toString(),signMethod});
parameters.put(OAuth.OAUTH_SIGNATURE_METHOD,signMethod);
parameters.put(OAuth.OAUTH_NONCE,UUID.randomUUID().toString());
parameters.put(OAuth.OAUTH_TIMESTAMP,String.valueOf(System.currentTimeMillis() / 1000));
parameters.put(OAuth.OAUTH_CONSUMER_KEY,OAuthTestUtils.CLIENT_ID);
OAuthMessage message=invokeRequestToken(parameters,style,OAuthServer.PORT);
boolean isFormEncoded=OAuth.isFormEncoded(message.getBodyType());
Assert.assertTrue(isFormEncoded);
List responseParams=OAuthTestUtils.getResponseParams(message);
String wwwHeader=message.getHeader("Authenticate");
Assert.assertNull(wwwHeader);
String callbacConf=OAuthTestUtils.findOAuthParameter(responseParams,OAuth.OAUTH_CALLBACK_CONFIRMED).getValue();
Assert.assertEquals("true",callbacConf);
String oauthToken=OAuthTestUtils.findOAuthParameter(responseParams,OAuth.OAUTH_TOKEN).getKey();
Assert.assertFalse(StringUtils.isEmpty(oauthToken));
String tokenSecret=OAuthTestUtils.findOAuthParameter(responseParams,OAuth.OAUTH_TOKEN_SECRET).getKey();
Assert.assertFalse(StringUtils.isEmpty(tokenSecret));
parameters.put(OAuth.OAUTH_CONSUMER_KEY,"wrong");
message=invokeRequestToken(parameters,style,OAuthServer.PORT);
String response=message.getHeader("oauth_problem");
Assert.assertEquals(OAuth.Problems.CONSUMER_KEY_UNKNOWN,response);
}
}
}
Class: org.apache.cxf.systest.jaxrs.security.oauth2.grants.JAXRSOAuth2Test APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testSAML2BearerGrant() throws Exception {
String address="https://localhost:" + PORT + "/oauth2/token";
WebClient wc=createWebClient(address);
Crypto crypto=new CryptoLoader().loadCrypto(CRYPTO_RESOURCE_PROPERTIES);
SelfSignInfo signInfo=new SelfSignInfo(crypto,"alice","password");
SamlCallbackHandler samlCallbackHandler=new SamlCallbackHandler(false);
String audienceURI="https://localhost:" + PORT + "/oauth2/token";
samlCallbackHandler.setAudience(audienceURI);
SamlAssertionWrapper assertionWrapper=SAMLUtils.createAssertion(samlCallbackHandler,signInfo);
Document doc=DOMUtils.newDocument();
Element assertionElement=assertionWrapper.toDOM(doc);
String assertion=DOM2Writer.nodeToString(assertionElement);
Saml2BearerGrant grant=new Saml2BearerGrant(assertion);
ClientAccessToken at=OAuthClientUtils.getAccessToken(wc,new Consumer("alice","alice"),grant,false);
assertNotNull(at.getTokenKey());
}
Class: org.apache.cxf.systest.jaxrs.security.saml.JAXRSSamlAuthorizationTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testPostBookAdminRoleWithGoodSubjectName() throws Exception {
String address="https://localhost:" + PORT + "/saml-roles2/bookstore/books";
Map props=new HashMap();
props.put("saml.roles",Collections.singletonList("admin"));
props.put("saml.subject.name","bob@mycompany.com");
WebClient wc=createWebClient(address,props);
wc.type(MediaType.APPLICATION_XML).accept(MediaType.APPLICATION_XML);
Book book=wc.post(new Book("CXF",125L),Book.class);
assertEquals(125L,book.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testPostBookAdminRole() throws Exception {
String address="https://localhost:" + PORT + "/saml-roles/bookstore/books";
WebClient wc=createWebClient(address,Collections.singletonMap("saml.roles",Collections.singletonList("admin")));
wc.type(MediaType.APPLICATION_XML).accept(MediaType.APPLICATION_XML);
Book book=wc.post(new Book("CXF",125L),Book.class);
assertEquals(125L,book.getId());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testPostBookAdminWithClaims() throws Exception {
String address="https://localhost:" + PORT + "/saml-claims/bookstore/books";
Map props=new HashMap();
props.put("saml.roles",Collections.singletonList("admin"));
props.put("saml.auth",Collections.singletonList("smartcard"));
WebClient wc=createWebClient(address,props);
wc.type(MediaType.APPLICATION_XML).accept(MediaType.APPLICATION_XML);
Book book=wc.post(new Book("CXF",125L),Book.class);
assertEquals(125L,book.getId());
}
Class: org.apache.cxf.systest.jaxrs.security.saml.JAXRSSamlTest APIUtilityVerifier BranchVerifier UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testGetBookSAMLTokenInForm() throws Exception {
String address="https://localhost:" + PORT + "/samlform/bookstore/books";
FormEncodingProvider
APIUtilityVerifier BranchVerifier UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testGetBookPreviousSAMLTokenAsHeader() throws Exception {
String address="https://localhost:" + PORT + "/samlheader/bookstore/books/123";
WebClient wc=createWebClientForExistingToken(address,new SamlHeaderOutInterceptor(),null);
try {
Book book=wc.get(Book.class);
assertEquals(123L,book.getId());
}
catch ( WebApplicationException ex) {
fail(ex.getMessage());
}
catch ( ProcessingException ex) {
if (ex.getCause() != null && ex.getCause().getMessage() != null) {
fail(ex.getCause().getMessage());
}
else {
fail(ex.getMessage());
}
}
}
InternalCallVerifier EqualityVerifier
@Test public void testInvalidSAMLTokenAsHeader() throws Exception {
String address="https://localhost:" + PORT + "/samlheader/bookstore/books/123";
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
bean.setAddress(address);
SpringBusFactory bf=new SpringBusFactory();
URL busFile=JAXRSSamlTest.class.getResource("client.xml");
Bus springBus=bf.createBus(busFile.toString());
bean.setBus(springBus);
WebClient wc=bean.createWebClient();
wc.header("Authorization","SAML invalid_grant");
Response r=wc.get();
assertEquals(401,r.getStatus());
}
APIUtilityVerifier BranchVerifier UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testGetBookSAMLTokenAsHeader() throws Exception {
String address="https://localhost:" + PORT + "/samlheader/bookstore/books/123";
WebClient wc=createWebClient(address,new SamlHeaderOutInterceptor(),null);
try {
Book book=wc.get(Book.class);
assertEquals(123L,book.getId());
}
catch ( WebApplicationException ex) {
fail(ex.getMessage());
}
catch ( ProcessingException ex) {
if (ex.getCause() != null && ex.getCause().getMessage() != null) {
fail(ex.getCause().getMessage());
}
else {
fail(ex.getMessage());
}
}
}
APIUtilityVerifier BranchVerifier UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testGetBookPreviousSAMLTokenInForm() throws Exception {
String address="https://localhost:" + PORT + "/samlform/bookstore/books";
FormEncodingProvider
Class: org.apache.cxf.systest.jaxrs.security.xml.JAXRSXmlSecTest InternalCallVerifier EqualityVerifier
@Test public void testOldConfiguration() throws Exception {
String address="https://localhost:" + test.port + "/xmlsig";
JAXRSClientFactoryBean bean=new JAXRSClientFactoryBean();
bean.setAddress(address);
SpringBusFactory bf=new SpringBusFactory();
URL busFile=JAXRSXmlSecTest.class.getResource("client.xml");
Bus springBus=bf.createBus(busFile.toString());
bean.setBus(springBus);
Map newProperties=new HashMap<>();
newProperties.put("ws-security.callback-handler","org.apache.cxf.systest.jaxrs.security.saml.KeystorePasswordCallback");
newProperties.put("ws-security.signature.username","alice");
String cryptoUrl="org/apache/cxf/systest/jaxrs/security/alice.properties";
newProperties.put("ws-security.signature.properties",cryptoUrl);
bean.setProperties(newProperties);
if (test.streaming) {
XmlSecOutInterceptor sigInterceptor=new XmlSecOutInterceptor();
sigInterceptor.setSignRequest(true);
bean.getOutInterceptors().add(sigInterceptor);
}
else {
XmlSigOutInterceptor sigInterceptor=new XmlSigOutInterceptor();
bean.getOutInterceptors().add(sigInterceptor);
}
bean.setServiceClass(BookStore.class);
BookStore store=bean.create(BookStore.class);
Book book=store.addBook(new Book("CXF",126L));
assertEquals(126L,book.getId());
}
Class: org.apache.cxf.systest.jaxrs.tracing.htrace.HTraceTracingCustomHeadersTest APIUtilityVerifier InternalCallVerifier EqualityVerifier ConditionMatcher HybridVerifier
@Test public void testThatNewChildSpanIsCreated(){
final Response r=createWebClient("/bookstore/books",htraceClientProvider).get();
assertEquals(Status.OK.getStatusCode(),r.getStatus());
assertThat((String)r.getHeaders().getFirst(CUSTOM_HEADER_SPAN_ID),notNullValue());
}
InternalCallVerifier EqualityVerifier ConditionMatcher HybridVerifier
@Test public void testThatNewSpanIsCreated(){
final SpanId spanId=SpanId.fromRandom();
final Response r=createWebClient("/bookstore/books").header(CUSTOM_HEADER_SPAN_ID,spanId.toString()).get();
assertEquals(Status.OK.getStatusCode(),r.getStatus());
assertThat((String)r.getHeaders().getFirst(CUSTOM_HEADER_SPAN_ID),equalTo(spanId.toString()));
}
Class: org.apache.cxf.systest.jaxrs.tracing.htrace.HTraceTracingTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier ConditionMatcher HybridVerifier
@Test public void testThatNewChildSpanIsCreatedWhenParentIsProvided(){
final Response r=createWebClient("/bookstore/books",htraceClientProvider).get();
assertEquals(Status.OK.getStatusCode(),r.getStatus());
assertThat(TestSpanReceiver.getAllSpans().size(),equalTo(3));
assertThat(TestSpanReceiver.getAllSpans().get(0).getDescription(),equalTo("Get Books"));
assertThat(TestSpanReceiver.getAllSpans().get(0).getParents().length,equalTo(1));
assertTrue(r.getHeaders().containsKey(TracerHeaders.DEFAULT_HEADER_SPAN_ID));
}
InternalCallVerifier EqualityVerifier ConditionMatcher HybridVerifier
@Test public void testThatCurrentSpanIsAnnotatedWithKeyValue(){
final SpanId spanId=SpanId.fromRandom();
final Response r=createWebClient("/bookstore/book/1").header(TracerHeaders.DEFAULT_HEADER_SPAN_ID,spanId.toString()).get();
assertEquals(Status.OK.getStatusCode(),r.getStatus());
assertThat(TestSpanReceiver.getAllSpans().size(),equalTo(1));
assertThat(TestSpanReceiver.getAllSpans().get(0).getDescription(),equalTo("GET bookstore/book/1"));
assertThat(TestSpanReceiver.getAllSpans().get(0).getKVAnnotations().size(),equalTo(1));
assertThat((String)r.getHeaders().getFirst(TracerHeaders.DEFAULT_HEADER_SPAN_ID),equalTo(spanId.toString()));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier ConditionMatcher HybridVerifier
@Test public void testThatNewSpanIsCreatedWhenNotProvidedUsingAsyncClient() throws Exception {
final WebClient client=createWebClient("/bookstore/books",htraceClientProvider);
final Future f=client.async().get();
final Response r=f.get(1,TimeUnit.SECONDS);
assertEquals(Status.OK.getStatusCode(),r.getStatus());
assertThat(TestSpanReceiver.getAllSpans().size(),equalTo(3));
assertThat(TestSpanReceiver.getAllSpans().get(0).getDescription(),equalTo("Get Books"));
assertThat(TestSpanReceiver.getAllSpans().get(1).getDescription(),equalTo("GET bookstore/books"));
assertThat(TestSpanReceiver.getAllSpans().get(2).getDescription(),equalTo("GET " + client.getCurrentURI()));
assertTrue(r.getHeaders().containsKey(TracerHeaders.DEFAULT_HEADER_SPAN_ID));
}
BooleanVerifier InternalCallVerifier EqualityVerifier ConditionMatcher HybridVerifier
@Test public void testThatNewSpanIsCreatedWhenNotProvided(){
final Response r=createWebClient("/bookstore/books").get();
assertEquals(Status.OK.getStatusCode(),r.getStatus());
assertThat(TestSpanReceiver.getAllSpans().size(),equalTo(2));
assertThat(TestSpanReceiver.getAllSpans().get(0).getDescription(),equalTo("Get Books"));
assertThat(TestSpanReceiver.getAllSpans().get(1).getDescription(),equalTo("GET bookstore/books"));
assertFalse(r.getHeaders().containsKey(TracerHeaders.DEFAULT_HEADER_SPAN_ID));
}
InternalCallVerifier EqualityVerifier ConditionMatcher HybridVerifier
@Test public void testThatParallelSpanIsAnnotatedWithTimeline(){
final SpanId spanId=SpanId.fromRandom();
final Response r=createWebClient("/bookstore/process").header(TracerHeaders.DEFAULT_HEADER_SPAN_ID,spanId.toString()).put("");
assertEquals(Status.OK.getStatusCode(),r.getStatus());
assertThat(TestSpanReceiver.getAllSpans().size(),equalTo(2));
assertThat(TestSpanReceiver.getAllSpans().get(0).getDescription(),equalTo("PUT bookstore/process"));
assertThat(TestSpanReceiver.getAllSpans().get(0).getTimelineAnnotations().size(),equalTo(0));
assertThat(TestSpanReceiver.getAllSpans().get(1).getDescription(),equalTo("Processing books"));
assertThat(TestSpanReceiver.getAllSpans().get(1).getTimelineAnnotations().size(),equalTo(1));
assertThat((String)r.getHeaders().getFirst(TracerHeaders.DEFAULT_HEADER_SPAN_ID),equalTo(spanId.toString()));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier ConditionMatcher HybridVerifier
@Test public void testThatProvidedSpanIsNotClosedWhenActive() throws MalformedURLException {
try (final TraceScope scope=tracer.newScope("test span")){
final Response r=createWebClient("/bookstore/books",htraceClientProvider).get();
assertEquals(Status.OK.getStatusCode(),r.getStatus());
assertThat(TestSpanReceiver.getAllSpans().size(),equalTo(2));
assertThat(TestSpanReceiver.getAllSpans().get(0).getDescription(),equalTo("Get Books"));
assertThat(TestSpanReceiver.getAllSpans().get(0).getParents().length,equalTo(1));
assertThat(TestSpanReceiver.getAllSpans().get(1).getDescription(),equalTo("GET bookstore/books"));
assertTrue(r.getHeaders().containsKey(TracerHeaders.DEFAULT_HEADER_SPAN_ID));
}
assertThat(TestSpanReceiver.getAllSpans().size(),equalTo(3));
assertThat(TestSpanReceiver.getAllSpans().get(2).getDescription(),equalTo("test span"));
}
InternalCallVerifier EqualityVerifier ConditionMatcher HybridVerifier
@Test public void testThatNewInnerSpanIsCreated(){
final SpanId spanId=SpanId.fromRandom();
final Response r=createWebClient("/bookstore/books").header(TracerHeaders.DEFAULT_HEADER_SPAN_ID,spanId.toString()).get();
assertEquals(Status.OK.getStatusCode(),r.getStatus());
assertThat(TestSpanReceiver.getAllSpans().size(),equalTo(2));
assertThat(TestSpanReceiver.getAllSpans().get(0).getDescription(),equalTo("Get Books"));
assertThat(TestSpanReceiver.getAllSpans().get(1).getDescription(),equalTo("GET bookstore/books"));
assertThat((String)r.getHeaders().getFirst(TracerHeaders.DEFAULT_HEADER_SPAN_ID),equalTo(spanId.toString()));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier ConditionMatcher HybridVerifier
@Test public void testThatProvidedSpanIsNotDetachedWhenActiveUsingAsyncClient() throws Exception {
final WebClient client=createWebClient("/bookstore/books",htraceClientProvider);
try (final TraceScope scope=tracer.newScope("test span")){
final Future f=client.async().get();
final Response r=f.get(1,TimeUnit.SECONDS);
assertEquals(Status.OK.getStatusCode(),r.getStatus());
assertThat(Tracer.getCurrentSpan(),equalTo(scope.getSpan()));
assertThat(TestSpanReceiver.getAllSpans().size(),equalTo(2));
assertThat(TestSpanReceiver.getAllSpans().get(0).getDescription(),equalTo("Get Books"));
assertThat(TestSpanReceiver.getAllSpans().get(1).getDescription(),equalTo("GET bookstore/books"));
assertTrue(r.getHeaders().containsKey(TracerHeaders.DEFAULT_HEADER_SPAN_ID));
}
assertThat(TestSpanReceiver.getAllSpans().get(2).getDescription(),equalTo("test span"));
}
InternalCallVerifier EqualityVerifier ConditionMatcher HybridVerifier
@Test public void testThatNewInnerSpanIsCreatedUsingAsyncInvocation(){
final SpanId spanId=SpanId.fromRandom();
final Response r=createWebClient("/bookstore/books/async").header(TracerHeaders.DEFAULT_HEADER_SPAN_ID,spanId.toString()).get();
assertEquals(Status.OK.getStatusCode(),r.getStatus());
assertThat(TestSpanReceiver.getAllSpans().size(),equalTo(2));
assertThat(TestSpanReceiver.getAllSpans().get(1).getDescription(),equalTo("GET bookstore/books/async"));
assertThat(TestSpanReceiver.getAllSpans().get(0).getDescription(),equalTo("Processing books"));
assertThat((String)r.getHeaders().getFirst(TracerHeaders.DEFAULT_HEADER_SPAN_ID),equalTo(spanId.toString()));
}
InternalCallVerifier EqualityVerifier ConditionMatcher HybridVerifier
@Test public void testThatOuterSpanIsCreatedUsingAsyncInvocation(){
final SpanId spanId=SpanId.fromRandom();
final Response r=createWebClient("/bookstore/books/async/notrace").header(TracerHeaders.DEFAULT_HEADER_SPAN_ID,spanId.toString()).get();
assertEquals(Status.OK.getStatusCode(),r.getStatus());
assertThat(TestSpanReceiver.getAllSpans().size(),equalTo(1));
assertThat(TestSpanReceiver.getAllSpans().get(0).getDescription(),equalTo("GET bookstore/books/async/notrace"));
assertThat((String)r.getHeaders().getFirst(TracerHeaders.DEFAULT_HEADER_SPAN_ID),equalTo(spanId.toString()));
}
InternalCallVerifier EqualityVerifier ConditionMatcher HybridVerifier
@Test public void testThatInnerSpanIsCreatedUsingPseudoAsyncInvocation(){
final SpanId spanId=SpanId.fromRandom();
final Response r=createWebClient("/bookstore/books/pseudo-async").header(TracerHeaders.DEFAULT_HEADER_SPAN_ID,spanId.toString()).get();
assertEquals(Status.OK.getStatusCode(),r.getStatus());
assertThat(TestSpanReceiver.getAllSpans().size(),equalTo(2));
assertThat(TestSpanReceiver.getAllSpans().get(1).getDescription(),equalTo("GET bookstore/books/pseudo-async"));
assertThat(TestSpanReceiver.getAllSpans().get(0).getDescription(),equalTo("Processing books"));
assertThat((String)r.getHeaders().getFirst(TracerHeaders.DEFAULT_HEADER_SPAN_ID),equalTo(spanId.toString()));
}
Class: org.apache.cxf.systest.jaxrs.validation.spring.JAXRSClientServerValidationSpringTest APIUtilityVerifier UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testHelloRestValidationFailsIfNameIsNull() throws Exception {
String address="http://localhost:" + PORT + "/bwrest";
BookWorld service=JAXRSClientFactory.create(address,BookWorld.class);
BookWithValidation bw=service.echoBook(new BookWithValidation("RS","123"));
assertEquals("123",bw.getId());
try {
service.echoBook(new BookWithValidation(null,"123"));
fail("Validation failure expected");
}
catch ( BadRequestException ex) {
}
}
APIUtilityVerifier UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testHelloSoapValidationFailsIfNameIsNull() throws Exception {
final QName serviceName=new QName("http://bookworld.com","BookWorld");
final QName portName=new QName("http://bookworld.com","BookWorldPort");
final String address="http://localhost:" + PORT + "/bwsoap";
Service service=Service.create(serviceName);
service.addPort(portName,SOAPBinding.SOAP11HTTP_BINDING,address);
BookWorld bwService=service.getPort(BookWorld.class);
BookWithValidation bw=bwService.echoBook(new BookWithValidation("WS","123"));
assertEquals("123",bw.getId());
try {
bwService.echoBook(new BookWithValidation(null,"123"));
fail("Validation failure expected");
}
catch ( SOAPFaultException ex) {
}
}
Class: org.apache.cxf.systest.jaxrs.websocket.JAXRSClientConduitWebSocketTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testBookWithWebSocket() throws Exception {
String address="ws://localhost:" + getPort() + "/websocket";
BookStoreWebSocket resource=JAXRSClientFactory.create(address,BookStoreWebSocket.class);
Client client=WebClient.client(resource);
client.header(HttpHeaders.USER_AGENT,JAXRSClientConduitWebSocketTest.class.getName());
assertEquals("CXF in Action",new String(resource.getBookName()));
assertEquals("CXF in Action",new String(resource.getBookName()));
Book book=resource.getBook(123);
assertEquals("CXF in Action",book.getName());
assertEquals(Long.valueOf(123),resource.echoBookId(123));
assertEquals(Long.valueOf(123),resource.echoBookId(123));
}
Class: org.apache.cxf.systest.jaxrs.websocket.JAXRSClientServerWebSocketSpringWebAppTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookHTTP() throws Exception {
String address="http://localhost:" + getPort() + getContext()+ "/http/web/bookstore/books/1";
WebClient wc=WebClient.create(address);
wc.accept("application/xml");
Book book=wc.get(Book.class);
assertEquals(1L,book.getId());
}
Class: org.apache.cxf.systest.jaxrs.websocket.JAXRSClientServerWebSocketTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testBookWithWebSocketAndHTTP() throws Exception {
String address="ws://localhost:" + getPort() + getContext()+ "/websocket/web/bookstore";
WebSocketTestClient wsclient=new WebSocketTestClient(address);
wsclient.connect();
try {
wsclient.sendMessage(("GET " + getContext() + "/websocket/web/bookstore/booknames").getBytes());
assertTrue("one book must be returned",wsclient.await(3));
List received=wsclient.getReceived();
assertEquals(1,received.size());
WebSocketTestClient.Response resp=new WebSocketTestClient.Response(received.get(0));
assertEquals(200,resp.getStatusCode());
assertEquals("text/plain",resp.getContentType());
String value=resp.getTextEntity();
assertEquals("CXF in Action",value);
testGetBookHTTPFromWebSocketEndpoint();
}
finally {
wsclient.close();
}
}
APIUtilityVerifier IterativeVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testGetBookStreamWithIDReferences() throws Exception {
String address="ws://localhost:" + getPort() + getContext()+ "/websocket/web/bookstore";
WebSocketTestClient wsclient=new WebSocketTestClient(address);
wsclient.connect();
try {
wsclient.reset(5);
String reqid=UUID.randomUUID().toString();
wsclient.sendMessage(("GET " + getContext() + "/websocket/web/bookstore/bookstream\r\nAccept: application/json\r\n"+ WebSocketConstants.DEFAULT_REQUEST_ID_KEY+ ": "+ reqid+ "\r\n\r\n").getBytes());
assertTrue("response expected",wsclient.await(5));
List received=wsclient.getReceivedResponses();
assertEquals(5,received.size());
WebSocketTestClient.Response resp=received.get(0);
assertEquals(200,resp.getStatusCode());
assertEquals("application/json",resp.getContentType());
String value=resp.getTextEntity();
assertEquals(value,getBookJson(1));
for (int i=2; i <= 5; i++) {
resp=received.get(i - 1);
assertEquals(0,resp.getStatusCode());
assertEquals(reqid,resp.getId());
assertEquals(resp.getTextEntity(),getBookJson(i));
}
}
finally {
wsclient.close();
}
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testCallsInParallel() throws Exception {
String address="ws://localhost:" + getPort() + getContext()+ "/websocket/web/bookstore";
WebSocketTestClient wsclient=new WebSocketTestClient(address);
wsclient.connect();
try {
wsclient.reset(2);
wsclient.sendTextMessage("GET " + getContext() + "/websocket/web/bookstore/hold/3000");
wsclient.sendTextMessage("GET " + getContext() + "/websocket/web/bookstore/hold/3000");
assertTrue("response expected",wsclient.await(4));
List received=wsclient.getReceivedResponses();
assertEquals(2,received.size());
}
finally {
wsclient.close();
}
}
APIUtilityVerifier IterativeVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testGetBookStream() throws Exception {
String address="ws://localhost:" + getPort() + getContext()+ "/websocket/web/bookstore";
WebSocketTestClient wsclient=new WebSocketTestClient(address);
wsclient.connect();
try {
wsclient.reset(5);
wsclient.sendMessage(("GET " + getContext() + "/websocket/web/bookstore/bookstream\r\nAccept: application/json\r\n\r\n").getBytes());
assertTrue("response expected",wsclient.await(5));
List received=wsclient.getReceivedResponses();
assertEquals(5,received.size());
WebSocketTestClient.Response resp=received.get(0);
assertEquals(200,resp.getStatusCode());
assertEquals("application/json",resp.getContentType());
String value=resp.getTextEntity();
assertEquals(value,getBookJson(1));
for (int i=2; i <= 5; i++) {
resp=received.get(i - 1);
assertEquals(0,resp.getStatusCode());
assertEquals(resp.getTextEntity(),getBookJson(i));
}
}
finally {
wsclient.close();
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testWrongMethod() throws Exception {
String address="ws://localhost:" + getPort() + getContext()+ "/websocket/web/bookstore";
WebSocketTestClient wsclient=new WebSocketTestClient(address);
wsclient.connect();
try {
wsclient.reset(1);
wsclient.sendMessage(("POST " + getContext() + "/websocket/web/bookstore/booknames").getBytes());
assertTrue("error response expected",wsclient.await(3));
List received=wsclient.getReceivedResponses();
assertEquals(1,received.size());
WebSocketTestClient.Response resp=received.get(0);
assertEquals(405,resp.getStatusCode());
}
finally {
wsclient.close();
}
}
APIUtilityVerifier IterativeVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testBookWithWebSocket() throws Exception {
String address="ws://localhost:" + getPort() + getContext()+ "/websocket/web/bookstore";
WebSocketTestClient wsclient=new WebSocketTestClient(address);
wsclient.connect();
try {
wsclient.sendMessage(("GET " + getContext() + "/websocket/web/bookstore/booknames").getBytes());
assertTrue("one book must be returned",wsclient.await(30000));
List received=wsclient.getReceivedResponses();
assertEquals(1,received.size());
WebSocketTestClient.Response resp=received.get(0);
assertEquals(200,resp.getStatusCode());
assertEquals("text/plain",resp.getContentType());
String value=resp.getTextEntity();
assertEquals("CXF in Action",value);
wsclient.reset(1);
wsclient.sendTextMessage("GET " + getContext() + "/websocket/web/bookstore/booknames");
assertTrue("one book must be returned",wsclient.await(3));
received=wsclient.getReceivedResponses();
assertEquals(1,received.size());
resp=received.get(0);
assertEquals(200,resp.getStatusCode());
assertEquals("text/plain",resp.getContentType());
value=resp.getTextEntity();
assertEquals("CXF in Action",value);
wsclient.reset(1);
wsclient.sendMessage(("GET " + getContext() + "/websocket/web/bookstore/books/123").getBytes());
assertTrue("response expected",wsclient.await(3));
received=wsclient.getReceivedResponses();
resp=received.get(0);
assertEquals(200,resp.getStatusCode());
assertEquals("application/xml",resp.getContentType());
value=resp.getTextEntity();
assertTrue(value.startsWith(""));
wsclient.reset(1);
wsclient.sendMessage(("POST " + getContext() + "/websocket/web/bookstore/booksplain\r\nContent-Type: text/plain\r\n\r\n123").getBytes());
assertTrue("response expected",wsclient.await(3));
received=wsclient.getReceivedResponses();
resp=received.get(0);
assertEquals(200,resp.getStatusCode());
assertEquals("text/plain",resp.getContentType());
value=resp.getTextEntity();
assertEquals("123",value);
wsclient.reset(1);
wsclient.sendTextMessage("POST " + getContext() + "/websocket/web/bookstore/booksplain\r\nContent-Type: text/plain\r\n\r\n123");
assertTrue("response expected",wsclient.await(3));
received=wsclient.getReceivedResponses();
resp=received.get(0);
assertEquals(200,resp.getStatusCode());
assertEquals("text/plain",resp.getContentType());
value=resp.getTextEntity();
assertEquals("123",value);
wsclient.reset(6);
wsclient.sendMessage(("GET " + getContext() + "/websocket/web/bookstore/bookbought").getBytes());
assertTrue("response expected",wsclient.await(5));
received=wsclient.getReceivedResponses();
assertEquals(6,received.size());
resp=received.get(0);
assertEquals(200,resp.getStatusCode());
assertEquals("application/octet-stream",resp.getContentType());
value=resp.getTextEntity();
assertTrue(value.startsWith("Today:"));
for (int r=2, i=1; i < 6; r*=2, i++) {
resp=received.get(i);
assertEquals(0,resp.getStatusCode());
assertEquals(r,Integer.parseInt(resp.getTextEntity()));
}
}
finally {
wsclient.close();
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testStreamRegisterAndUnregister() throws Exception {
String address="ws://localhost:" + getPort() + getContext()+ "/websocket/web/bookstore";
WebSocketTestClient wsclient1=new WebSocketTestClient(address);
WebSocketTestClient wsclient2=new WebSocketTestClient(address);
wsclient1.connect();
wsclient2.connect();
try {
String regkey=UUID.randomUUID().toString();
EventCreatorRunner runner=new EventCreatorRunner(wsclient2,regkey,1000,1000);
new Thread(runner).start();
wsclient1.reset(3);
wsclient1.sendTextMessage("GET " + getContext() + "/websocket/web/bookstore/events/register\r\n"+ WebSocketConstants.DEFAULT_REQUEST_ID_KEY+ ": "+ regkey+ "\r\n\r\n");
assertFalse("only 2 responses expected",wsclient1.await(5));
List received=wsclient1.getReceivedResponses();
assertEquals(2,received.size());
WebSocketTestClient.Response resp=received.get(0);
assertEquals(200,resp.getStatusCode());
assertEquals("text/plain",resp.getContentType());
String value=resp.getTextEntity();
assertTrue(value.startsWith("Registered " + regkey));
String id=resp.getId();
assertEquals("unexpected responseId",regkey,id);
resp=received.get(1);
assertEquals(0,resp.getStatusCode());
value=resp.getTextEntity();
assertEquals("News: event Hello created",value);
id=resp.getId();
assertEquals("unexpected responseId",regkey,id);
String[] values=runner.getValues();
assertTrue(runner.isCompleted());
assertEquals("Hello created",values[0]);
assertTrue(values[1].startsWith("Unregistered: " + regkey));
assertEquals("Hola created",values[2]);
}
finally {
wsclient1.close();
wsclient2.close();
}
}
APIUtilityVerifier BranchVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCallsWithIDReferences() throws Exception {
String address="ws://localhost:" + getPort() + getContext()+ "/websocket/web/bookstore";
WebSocketTestClient wsclient=new WebSocketTestClient(address);
wsclient.connect();
try {
wsclient.sendTextMessage("POST " + getContext() + "/websocket/web/bookstore/booksplain\r\nContent-Type: text/plain\r\n\r\n459");
assertTrue("response expected",wsclient.await(3));
List received=wsclient.getReceivedResponses();
WebSocketTestClient.Response resp=received.get(0);
assertEquals(200,resp.getStatusCode());
assertEquals("text/plain",resp.getContentType());
String value=resp.getTextEntity();
assertEquals("459",value);
String id=resp.getId();
assertNull("response id is incorrect",id);
wsclient.reset(2);
String reqid1=UUID.randomUUID().toString();
String reqid2=UUID.randomUUID().toString();
wsclient.sendTextMessage("POST " + getContext() + "/websocket/web/bookstore/booksplain\r\nContent-Type: text/plain\r\n"+ WebSocketConstants.DEFAULT_REQUEST_ID_KEY+ ": "+ reqid1+ "\r\n\r\n549");
wsclient.sendTextMessage("POST " + getContext() + "/websocket/web/bookstore/booksplain\r\nContent-Type: text/plain\r\n"+ WebSocketConstants.DEFAULT_REQUEST_ID_KEY+ ": "+ reqid2+ "\r\n\r\n495");
assertTrue("response expected",wsclient.await(3));
received=wsclient.getReceivedResponses();
for ( WebSocketTestClient.Response r : received) {
assertEquals(200,r.getStatusCode());
assertEquals("text/plain",r.getContentType());
value=r.getTextEntity();
id=r.getId();
if (reqid1.equals(id)) {
assertEquals("549",value);
}
else if (reqid2.equals(id)) {
assertEquals("495",value);
}
else {
fail("unexpected responseId: " + id);
}
}
}
finally {
wsclient.close();
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetBookHTTPFromWebSocketEndpoint() throws Exception {
String address="http://localhost:" + getPort() + getContext()+ "/websocket/web/bookstore/books/1";
WebClient wc=WebClient.create(address);
wc.accept("application/xml");
Book book=wc.get(Book.class);
assertEquals(1L,book.getId());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testBookWithWebSocketServletStream() throws Exception {
String address="ws://localhost:" + getPort() + getContext()+ "/websocket/web/bookstore";
WebSocketTestClient wsclient=new WebSocketTestClient(address);
wsclient.connect();
try {
wsclient.sendMessage(("GET " + getContext() + "/websocket/web/bookstore/booknames/servletstream").getBytes());
assertTrue("one book must be returned",wsclient.await(3));
List received=wsclient.getReceivedResponses();
assertEquals(1,received.size());
WebSocketTestClient.Response resp=received.get(0);
assertEquals(200,resp.getStatusCode());
assertEquals("text/plain",resp.getContentType());
String value=resp.getTextEntity();
assertEquals("CXF in Action",value);
}
finally {
wsclient.close();
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testPathRestriction() throws Exception {
String address="ws://localhost:" + getPort() + getContext()+ "/websocket/web/bookstore";
WebSocketTestClient wsclient=new WebSocketTestClient(address);
wsclient.connect();
try {
wsclient.sendMessage(("GET " + getContext() + "/websocket/bookstore2").getBytes());
assertTrue("error response expected",wsclient.await(3));
List received=wsclient.getReceivedResponses();
assertEquals(1,received.size());
WebSocketTestClient.Response resp=received.get(0);
assertEquals(400,resp.getStatusCode());
}
finally {
wsclient.close();
}
}
Class: org.apache.cxf.systest.jaxws.AnyClientServerTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testAny() throws Exception {
URL wsdl=getClass().getResource("/wsdl/any.wsdl");
assertNotNull(wsdl);
SOAPService ss=new SOAPService(wsdl,serviceName);
Greeter port=ss.getSoapPort();
updateAddressPort(port,PORT);
List any=new ArrayList();
Port anyPort=new Port();
Port anyPort1=new Port();
JAXBElement ele1=new JAXBElement(new QName("http://apache.org/hello_world_soap_http/other","port"),String.class,"hello");
anyPort.setAny(ele1);
JAXBElement ele2=new JAXBElement(new QName("http://apache.org/hello_world_soap_http/other","port"),String.class,"Bon");
anyPort1.setAny(ele2);
any.add(anyPort);
any.add(anyPort1);
String rep=port.sayHi(any);
assertEquals(rep,"helloBon");
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testList() throws Exception {
URL wsdl=getClass().getResource("/wsdl/any.wsdl");
assertNotNull(wsdl);
SOAPService ss=new SOAPService(wsdl,serviceName);
Greeter port=ss.getSoapPort();
updateAddressPort(port,PORT);
List list=new ArrayList();
org.apache.hello_world_soap_http.any_types.SayHi1.Port port1=new org.apache.hello_world_soap_http.any_types.SayHi1.Port();
port1.setRequestType("hello");
org.apache.hello_world_soap_http.any_types.SayHi1.Port port2=new org.apache.hello_world_soap_http.any_types.SayHi1.Port();
port2.setRequestType("Bon");
list.add(port1);
list.add(port2);
String rep=port.sayHi1(list);
assertEquals(rep,"helloBon");
}
Class: org.apache.cxf.systest.jaxws.CXF6655Test InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testConnection() throws Exception {
QName serviceName=new QName("http://cxf.apache.org/systest/jaxws/","HelloService");
HelloService service=new HelloService(null,serviceName);
assertNotNull(service);
Hello hello=service.getHelloPort();
((BindingProvider)hello).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"http://localhost:" + PORT + "/hello");
assertEquals("getSayHi",hello.sayHi("SayHi"));
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testConnectionWithProxy() throws Exception {
QName serviceName=new QName("http://cxf.apache.org/systest/jaxws/","HelloService");
HelloService service=new HelloService(null,serviceName);
assertNotNull(service);
Hello hello=service.getHelloPort();
Client client=ClientProxy.getClient(hello);
client.getInInterceptors().add(new LoggingInInterceptor());
client.getOutInterceptors().add(new LoggingOutInterceptor());
HTTPConduit http=(HTTPConduit)client.getConduit();
HTTPClientPolicy httpClientPolicy=new HTTPClientPolicy();
httpClientPolicy.setAllowChunking(false);
httpClientPolicy.setReceiveTimeout(0);
httpClientPolicy.setProxyServerType(ProxyServerType.HTTP);
httpClientPolicy.setProxyServer("localhost");
httpClientPolicy.setProxyServerPort(PROXY_PORT);
http.setClient(httpClientPolicy);
((BindingProvider)hello).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"http://localhost:" + PORT + "/hello");
assertEquals("getSayHi",hello.sayHi("SayHi"));
}
Class: org.apache.cxf.systest.jaxws.ClientServerGreeterBaseNoWsdlTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testInvocation() throws Exception {
GreeterService service=new GreeterService();
assertNotNull(service);
try {
Greeter greeter=service.getGreeterPort();
updateAddressPort(greeter,PORT);
String greeting=greeter.greetMe("Bonjour");
assertNotNull("no response received from service",greeting);
assertEquals("Hello Bonjour",greeting);
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
Class: org.apache.cxf.systest.jaxws.ClientServerGreeterBaseTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testInvocation() throws Exception {
GreeterService service=new GreeterService();
assertNotNull(service);
try {
Greeter greeter=service.getGreeterPort();
updateAddressPort(greeter,PORT);
String greeting=greeter.greetMe("Bonjour");
assertNotNull("no response received from service",greeting);
assertEquals("Hello Bonjour",greeting);
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
Class: org.apache.cxf.systest.jaxws.ClientServerGreeterNoWsdlTest APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testWSDLImports() throws Exception {
URL url=new URL("http://localhost:" + PORT + "/SoapContext/GreeterPort?wsdl");
Document doc=StaxUtils.read(url.openStream());
Map ns=new HashMap();
ns.put("xsd","http://www.w3.org/2001/XMLSchema");
Node nd=new XPathUtils(ns).getValueNode("//xsd:import[@namespace='http://cxf.apache.org/greeter_control/types']",doc.getDocumentElement());
assertNotNull(nd);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testInvocation() throws Exception {
GreeterService service=new GreeterService();
assertNotNull(service);
try {
Greeter greeter=service.getGreeterPort();
updateAddressPort(greeter,PORT);
String greeting=greeter.greetMe("Bonjour");
assertNotNull("no response received from service",greeting);
assertEquals("Hello Bonjour",greeting);
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
Class: org.apache.cxf.systest.jaxws.ClientServerMiscTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSimpleClientWithWsdl() throws Exception {
QName portName=new QName("http://cxf.apache.org/systest/jaxws/DocLitWrappedCodeFirstService","DocLitWrappedCodeFirstServicePort");
QName servName=new QName("http://cxf.apache.org/systest/jaxws/DocLitWrappedCodeFirstService","DocLitWrappedCodeFirstService");
ClientProxyFactoryBean factory=new ClientProxyFactoryBean();
factory.setWsdlURL(ServerMisc.DOCLIT_CODEFIRST_URL + "?wsdl");
factory.setServiceName(servName);
factory.setServiceClass(DocLitWrappedCodeFirstService.class);
factory.setEndpointName(portName);
DocLitWrappedCodeFirstService port=(DocLitWrappedCodeFirstService)factory.create();
assertNotNull(port);
String echoMsg=port.echo("Hello");
assertEquals("Hello",echoMsg);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testRefAnonymousComplexType() throws Exception {
AnonymousComplexTypeService actService=new AnonymousComplexTypeService();
assertNotNull(actService);
QName portName=new QName("http://cxf.apache.org/anonymous_complex_type/","anonymous_complex_typeSOAP");
AnonymousComplexType act=actService.getPort(portName,AnonymousComplexType.class);
updateAddressPort(act,PORT);
try {
SplitName name=new SplitName();
name.setName("Tom Li");
RefSplitName refName=new RefSplitName();
refName.setSplitName(name);
RefSplitNameResponse reply=act.refSplitName(refName);
assertNotNull("no response received from service",reply);
assertEquals("Tom",reply.getSplitNameResponse().getNames().getFirst());
assertEquals("Li",reply.getSplitNameResponse().getNames().getSecond());
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testMissingMethods() throws Exception {
QName portName=new QName("http://cxf.apache.org/systest/jaxws/DocLitWrappedCodeFirstService","DocLitWrappedCodeFirstServicePort");
QName servName=new QName("http://cxf.apache.org/systest/jaxws/DocLitWrappedCodeFirstService","DocLitWrappedCodeFirstService");
Service service=Service.create(new URL(ServerMisc.DOCLIT_CODEFIRST_URL + "?wsdl"),servName);
DocLitWrappedCodeFirstServiceMissingOps port=service.getPort(portName,DocLitWrappedCodeFirstServiceMissingOps.class);
((BindingProvider)port).getEndpointReference();
int[] ret=port.echoIntArray(new int[]{1,2});
assertNotNull(ret);
ret=port.echoIntArray(new int[]{1,2});
assertNotNull(ret);
ret=port.echoIntArray(new int[]{1,2});
assertNotNull(ret);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testMinOccursAndNillableJAXBElement() throws Exception {
JaxbElementTest_Service service=new JaxbElementTest_Service();
assertNotNull(service);
JaxbElementTest port=service.getPort(JaxbElementTest.class);
updateAddressPort(port,PORT);
try {
String response=port.newOperation("hello");
assertNotNull(response);
assertEquals("in=hello",response);
response=port.newOperation(null);
assertNotNull(response);
assertEquals("in=null",response);
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
InternalCallVerifier EqualityVerifier
@Test public void testWSDLDocs() throws Exception {
Map ns=new HashMap();
ns.put("wsdl",WSDLConstants.NS_WSDL11);
XPathUtils xpu=new XPathUtils(ns);
Document wsdl=StaxUtils.read(this.getHttpConnection(ServerMisc.DOCLIT_CODEFIRST_URL + "?wsdl").getInputStream());
assertEquals("DocLitWrappedCodeFirstService impl",xpu.getValue("/wsdl:definitions/wsdl:service/wsdl:documentation",wsdl.getDocumentElement(),XPathConstants.STRING));
assertEquals("DocLitWrappedCodeFirstService interface",xpu.getValue("/wsdl:definitions/wsdl:portType/wsdl:documentation",wsdl.getDocumentElement(),XPathConstants.STRING));
assertEquals("DocLitWrappedCodeFirstService top level doc",xpu.getValue("/wsdl:definitions/wsdl:documentation",wsdl.getDocumentElement(),XPathConstants.STRING));
assertEquals("DocLitWrappedCodeFirstService binding doc",xpu.getValue("/wsdl:definitions/wsdl:binding/wsdl:documentation",wsdl.getDocumentElement(),XPathConstants.STRING));
assertEquals("DocLitWrappedCodeFirstService service/port doc",xpu.getValue("/wsdl:definitions/wsdl:service/wsdl:port/wsdl:documentation",wsdl.getDocumentElement(),XPathConstants.STRING));
assertEquals("multiInOut doc",xpu.getValue("/wsdl:definitions/wsdl:portType/wsdl:operation[@name='multiInOut']" + "/wsdl:documentation",wsdl.getDocumentElement(),XPathConstants.STRING));
assertEquals("multiInOut Input doc",xpu.getValue("/wsdl:definitions/wsdl:portType/wsdl:operation[@name='multiInOut']" + "/wsdl:input/wsdl:documentation",wsdl.getDocumentElement(),XPathConstants.STRING));
assertEquals("multiInOut Output doc",xpu.getValue("/wsdl:definitions/wsdl:portType/wsdl:operation[@name='multiInOut']" + "/wsdl:output/wsdl:documentation",wsdl.getDocumentElement(),XPathConstants.STRING));
assertEquals("multiInOut InputMessage doc",xpu.getValue("/wsdl:definitions/wsdl:message[@name='multiInOut']" + "/wsdl:documentation",wsdl.getDocumentElement(),XPathConstants.STRING));
assertEquals("multiInOut OutputMessage doc",xpu.getValue("/wsdl:definitions/wsdl:message[@name='multiInOutResponse']" + "/wsdl:documentation",wsdl.getDocumentElement(),XPathConstants.STRING));
assertEquals("multiInOut binding doc",xpu.getValue("/wsdl:definitions/wsdl:binding/wsdl:operation[@name='multiInOut']" + "/wsdl:documentation",wsdl.getDocumentElement(),XPathConstants.STRING));
assertEquals("multiInOut binding Input doc",xpu.getValue("/wsdl:definitions/wsdl:binding/wsdl:operation[@name='multiInOut']" + "/wsdl:input/wsdl:documentation",wsdl.getDocumentElement(),XPathConstants.STRING));
assertEquals("multiInOut binding Output doc",xpu.getValue("/wsdl:definitions/wsdl:binding/wsdl:operation[@name='multiInOut']" + "/wsdl:output/wsdl:documentation",wsdl.getDocumentElement(),XPathConstants.STRING));
assertEquals("fault binding doc",xpu.getValue("/wsdl:definitions/wsdl:binding/wsdl:operation[@name='throwException']" + "/wsdl:fault/wsdl:documentation",wsdl.getDocumentElement(),XPathConstants.STRING));
assertEquals("fault porttype doc",xpu.getValue("/wsdl:definitions/wsdl:portType/wsdl:operation[@name='throwException']" + "/wsdl:fault/wsdl:documentation",wsdl.getDocumentElement(),XPathConstants.STRING));
assertEquals("fault message doc",xpu.getValue("/wsdl:definitions/wsdl:message[@name='CustomException']" + "/wsdl:documentation",wsdl.getDocumentElement(),XPathConstants.STRING));
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testAnonymousComplexType() throws Exception {
AnonymousComplexTypeService actService=new AnonymousComplexTypeService();
assertNotNull(actService);
QName portName=new QName("http://cxf.apache.org/anonymous_complex_type/","anonymous_complex_typeSOAP");
AnonymousComplexType act=actService.getPort(portName,AnonymousComplexType.class);
updateAddressPort(act,PORT);
try {
Names reply=act.splitName("Tom Li");
assertNotNull("no response received from service",reply);
assertEquals("Tom",reply.getFirst());
assertEquals("Li",reply.getSecond());
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testInheritedTypesInOtherPackage() throws Exception {
InheritService serv=new InheritService();
Inherit port=serv.getInheritPort();
updateAddressPort(port,PORT);
ObjectInfo obj=port.getObject(0);
assertNotNull(obj);
assertNotNull(obj.getBaseObject());
assertEquals("A",obj.getBaseObject().getName());
assertTrue(obj.getBaseObject() instanceof SubTypeA);
obj=port.getObject(1);
assertNotNull(obj);
assertNotNull(obj.getBaseObject());
assertEquals("B",obj.getBaseObject().getName());
assertTrue(obj.getBaseObject() instanceof SubTypeB);
}
APIUtilityVerifier UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testDocLitBare() throws Exception {
QName portName=new QName("http://cxf.apache.org/systest/jaxws/DocLitBareCodeFirstService","DocLitBareCodeFirstServicePort");
QName servName=new QName("http://cxf.apache.org/systest/jaxws/DocLitBareCodeFirstService","DocLitBareCodeFirstService");
Service service=Service.create(servName);
service.addPort(portName,SOAPBinding.SOAP11HTTP_BINDING,ServerMisc.DOCLITBARE_CODEFIRST_URL);
DocLitBareCodeFirstService port=service.getPort(portName,DocLitBareCodeFirstService.class);
DocLitBareCodeFirstService.GreetMeRequest req=new DocLitBareCodeFirstService.GreetMeRequest();
DocLitBareCodeFirstService.GreetMeResponse resp;
BigInteger i[];
req.setName("Foo");
resp=port.greetMe(req);
assertEquals(req.getName(),resp.getName());
i=port.sayTest(new DocLitBareCodeFirstService.SayTestRequest("Dan"));
assertEquals(4,i.length);
assertEquals(0,i[0].intValue());
assertEquals(1,i[1].intValue());
assertEquals(2,i[2].intValue());
assertEquals(3,i[3].intValue());
service=Service.create(new URL(ServerMisc.DOCLITBARE_CODEFIRST_URL + "?wsdl"),servName);
port=service.getPort(portName,DocLitBareCodeFirstService.class);
resp=port.greetMe(req);
assertEquals(req.getName(),resp.getName());
req.setName("fault");
try {
resp=port.greetMe(req);
fail("did not get fault back");
}
catch ( SOAPFaultException ex) {
assertEquals("mr.actor",ex.getFault().getFaultActor());
assertEquals("test",ex.getFault().getDetail().getFirstChild().getLocalName());
}
req.setName("emptyfault");
try {
resp=port.greetMe(req);
fail("did not get fault back");
}
catch ( SOAPFaultException ex) {
assertNull(ex.getFault().getDetail());
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testAnonymousMinOccursConfig() throws Exception {
HttpURLConnection httpConnection=getHttpConnection(ServerMisc.DOCLIT_CODEFIRST_SETTINGS_URL + "?wsdl");
httpConnection.connect();
assertEquals(200,httpConnection.getResponseCode());
assertEquals("OK",httpConnection.getResponseMessage());
InputStream in=httpConnection.getInputStream();
assertNotNull(in);
Document doc=StaxUtils.read(in);
assertNotNull(doc);
Map ns=new HashMap();
ns.put("soap",Soap11.SOAP_NAMESPACE);
ns.put("tns","http://cxf.apache.org/systest/jaxws/DocLitWrappedCodeFirstService");
ns.put("wsdl","http://schemas.xmlsoap.org/wsdl/");
ns.put("xs","http://www.w3.org/2001/XMLSchema");
XPathUtils xu=new XPathUtils(ns);
Node ct=(Node)xu.getValue("//wsdl:definitions/wsdl:types/xs:schema" + "/xs:element[@name='getFooSetResponse']/xs:complexType/xs:sequence",doc,XPathConstants.NODE);
assertNotNull(ct);
ct=(Node)xu.getValue("//wsdl:definitions/wsdl:types/xs:schema" + "/xs:element[@name='multiInOut']/xs:complexType/xs:sequence" + "/xs:element[@nillable='true']",doc,XPathConstants.NODE);
assertNotNull(ct);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testInterfaceExtension() throws Exception {
QName portName=new QName("http://cxf.apache.org/systest/jaxws/DocLitWrappedCodeFirstBaseService","DocLitWrappedCodeFirstBaseServicePort");
QName servName=new QName("http://cxf.apache.org/systest/jaxws/DocLitWrappedCodeFirstBaseService","DocLitWrappedCodeFirstBaseService");
Service service=Service.create(servName);
service.addPort(portName,SOAPBinding.SOAP11HTTP_BINDING,ServerMisc.DOCLIT_CODEFIRST_BASE_URL);
DocLitWrappedCodeFirstBaseService port=service.getPort(portName,DocLitWrappedCodeFirstBaseService.class);
assertEquals(1,port.operationInBase(1));
assertEquals(2,port.operationInSub1(2));
assertEquals(3,port.operationInSub2(3));
service=Service.create(new URL(ServerMisc.DOCLIT_CODEFIRST_BASE_URL + "?wsdl"),servName);
port=service.getPort(portName,DocLitWrappedCodeFirstBaseService.class);
assertEquals(1,port.operationInBase(1));
assertEquals(2,port.operationInSub1(2));
assertEquals(3,port.operationInSub2(3));
}
Class: org.apache.cxf.systest.jaxws.ClientServerMixedStyleTest UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testMixedStyle() throws Exception {
SOAPService service=new SOAPService();
assertNotNull(service);
try {
Greeter greeter=service.getPort(portName,Greeter.class);
updateAddressPort(greeter,PORT);
GreetMe1 request=new GreetMe1();
request.setRequestType("Bonjour");
GreetMeResponse greeting=greeter.greetMe(request);
assertNotNull("no response received from service",greeting);
assertEquals("Hello Bonjour",greeting.getResponseType());
String reply=greeter.sayHi();
assertNotNull("no response received from service",reply);
assertEquals("Bonjour",reply);
try {
greeter.pingMe();
fail("expected exception not caught");
}
catch ( org.apache.hello_world_mixedstyle.PingMeFault f) {
}
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testCXF885() throws Exception {
Service serv=Service.create(new QName("http://example.com","MixedTest"));
MixedTest test=serv.getPort(MixedTest.class);
((BindingProvider)test).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"http://localhost:" + PORT + "/cxf885");
String ret=test.hello("A","B");
assertEquals("Hello A and B",ret);
String ret2=test.simple("Dan");
assertEquals("Hello Dan",ret2);
String ret3=test.tripple("A","B","C");
assertEquals("Tripple: A B C",ret3);
String ret4=test.simple2(24);
assertEquals("Int: 24",ret4);
serv=Service.create(new URL("http://localhost:" + PORT + "/cxf885?wsdl"),new QName("http://example.com","MixedTestImplService"));
test=serv.getPort(new QName("http://example.com","MixedTestImplPort"),MixedTest.class);
ret=test.hello("A","B");
assertEquals("Hello A and B",ret);
ret2=test.simple("Dan");
assertEquals("Hello Dan",ret2);
ret3=test.tripple("A","B","C");
assertEquals("Tripple: A B C",ret3);
ret4=test.simple2(24);
assertEquals("Int: 24",ret4);
}
Class: org.apache.cxf.systest.jaxws.ClientServerPartialWsdlTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCXF4676Partial1() throws Exception {
DynamicClientFactory dcf=DynamicClientFactory.newInstance();
Client client=dcf.createClient("http://localhost:" + PORT + "/AddNumbersImplPartial1Service?wsdl",serviceName1,portName1);
updateAddressPort(client,PORT);
Object[] result=client.invoke("addTwoNumbers",10,20);
assertNotNull("no response received from service",result);
assertEquals(30,result[0]);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCXF4676partial2() throws Exception {
DynamicClientFactory dcf=DynamicClientFactory.newInstance();
Client client=dcf.createClient("http://localhost:" + PORT + "/AddNumbersImplPartial2Service?wsdl",serviceName2,portName2);
updateAddressPort(client,PORT);
Object[] result=client.invoke("addTwoNumbers",10,20);
assertNotNull("no response received from service",result);
assertEquals(30,result[0]);
}
Class: org.apache.cxf.systest.jaxws.ClientServerRPCLitDefatulAnnoTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBasicConnection() throws Exception {
QName serviceName=new QName("http://cxf.apache.org/systest/jaxws/","HelloService");
HelloService service=new HelloService(getClass().getResource("/wsdl/others/hello.wsdl"),serviceName);
assertNotNull(service);
Hello hello=service.getHelloPort();
updateAddressPort(hello,PORT);
assertEquals("getSayHi",hello.sayHi("SayHi"));
}
Class: org.apache.cxf.systest.jaxws.ClientServerRPCLitTest BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testComplexType() throws Exception {
SOAPServiceRPCLit service=new SOAPServiceRPCLit();
assertNotNull(service);
GreeterRPCLit greeter=service.getPort(portName,GreeterRPCLit.class);
updateAddressPort(greeter,PORT);
MyComplexStruct in=new MyComplexStruct();
in.setElem1("elem1");
in.setElem2("elem2");
in.setElem3(45);
try {
((BindingProvider)greeter).getRequestContext().put(Message.SCHEMA_VALIDATION_ENABLED,Boolean.TRUE);
MyComplexStruct out=greeter.sendReceiveData(in);
assertNotNull("no response received from service",out);
assertEquals(in.getElem1(),out.getElem1());
assertEquals(in.getElem2(),out.getElem2());
assertEquals(in.getElem3(),out.getElem3());
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
try {
in.setElem2("invalid");
greeter.sendReceiveData(in);
}
catch ( SOAPFaultException f) {
assertTrue(f.getCause() instanceof UnmarshalException);
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testNoElementParts() throws Exception {
HttpURLConnection httpConnection=getHttpConnection("http://localhost:" + PORT + "/TestRPCWsdl?wsdl");
httpConnection.connect();
assertEquals(200,httpConnection.getResponseCode());
assertEquals("OK",httpConnection.getResponseMessage());
InputStream in=httpConnection.getInputStream();
assertNotNull(in);
Document doc=StaxUtils.read(in);
assertNotNull(doc);
Map ns=new HashMap();
ns.put("soap",Soap11.SOAP_NAMESPACE);
ns.put("wsdl","http://schemas.xmlsoap.org/wsdl/");
ns.put("xs","http://www.w3.org/2001/XMLSchema");
XPathUtils xu=new XPathUtils(ns);
NodeList ct=(NodeList)xu.getValue("//wsdl:definitions/wsdl:message/wsdl:part[@element != '']",doc,XPathConstants.NODESET);
assertNotNull(ct);
assertEquals(0,ct.getLength());
ct=(NodeList)xu.getValue("//wsdl:definitions/wsdl:message/wsdl:part[@type != '']",doc,XPathConstants.NODESET);
assertEquals(4,ct.getLength());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testDispatchClient() throws Exception {
SOAPServiceRPCLit service=new SOAPServiceRPCLit();
Dispatch disp=service.createDispatch(portName,Source.class,javax.xml.ws.Service.Mode.PAYLOAD);
updateAddressPort(disp,PORT);
String req="" + "" + "elem1 elem2 45 "+ " ";
Source source=new StreamSource(new StringReader(req));
Source resp=disp.invoke(source);
assertNotNull(resp);
Node nd=StaxUtils.read(resp);
if (nd instanceof Document) {
nd=((Document)nd).getDocumentElement();
}
XPathUtils xpu=new XPathUtils(new W3CNamespaceContext((Element)nd));
assertTrue(xpu.isExist("/ns1:sendReceiveDataResponse/out",nd,XPathConstants.NODE));
}
IterativeVerifier UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBasicConnection() throws Exception {
SOAPServiceRPCLit service=new SOAPServiceRPCLit();
assertNotNull(service);
String response1=new String("Hello Milestone-");
String response2=new String("Bonjour");
try {
GreeterRPCLit greeter=service.getPort(portName,GreeterRPCLit.class);
ClientProxy.getClient(greeter).getInInterceptors().add(new LoggingInInterceptor());
updateAddressPort(greeter,PORT);
for (int idx=0; idx < 1; idx++) {
String greeting=greeter.greetMe("Milestone-" + idx);
assertNotNull("no response received from service",greeting);
String exResponse=response1 + idx;
assertEquals(exResponse,greeting);
String reply=greeter.sayHi();
assertNotNull("no response received from service",reply);
assertEquals(response2,reply);
try {
greeter.greetMe("return null");
fail("should catch WebServiceException");
}
catch ( WebServiceException e) {
}
catch ( Exception e) {
fail("should catch WebServiceException");
throw e;
}
try {
greeter.greetMe(null);
fail("should catch WebServiceException");
}
catch ( WebServiceException e) {
}
catch ( Exception e) {
fail("should catch WebServiceException");
throw e;
}
}
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
Class: org.apache.cxf.systest.jaxws.ClientServerTest UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testFaultStackTrace() throws Exception {
System.setProperty("cxf.config.file.url",getClass().getResource("fault-stack-trace.xml").toString());
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
ExecutorService ex=Executors.newFixedThreadPool(1);
service.setExecutor(ex);
assertNotNull(service);
Greeter greeter=service.getPort(portName,Greeter.class);
updateAddressPort(greeter,PORT);
try {
greeter.testDocLitFault("");
fail("Should have thrown Runtime exception");
}
catch ( WebServiceException e) {
assertEquals("can't get back original message","Unknown source",e.getCause().getMessage());
assertTrue(e.getCause().getStackTrace().length > 0);
}
}
InternalCallVerifier EqualityVerifier
@Test public void testCXF2419() throws Exception {
org.apache.cxf.hello_world.elrefs.SOAPService serv=new org.apache.cxf.hello_world.elrefs.SOAPService();
org.apache.cxf.hello_world.elrefs.Greeter g=serv.getSoapPort();
updateAddressPort(g,PORT);
assertEquals("Hello CXF",g.greetMe("CXF"));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testAddPortWithSpecifiedSoap12Binding() throws Exception {
Service service=Service.create(serviceName);
service.addPort(fakePortName,javax.xml.ws.soap.SOAPBinding.SOAP12HTTP_BINDING,"http://localhost:" + PORT + "/SoapContext/SoapPort");
Greeter greeter=service.getPort(fakePortName,Greeter.class);
String response=new String("Bonjour");
try {
greeter.greetMe("test");
String reply=greeter.sayHi();
assertNotNull("no response received from service",reply);
assertEquals(response,reply);
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testMultiPorts() throws Exception {
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
QName sname=new QName("http://apache.org/hello_world_soap_http","SOAPServiceMultiPortTypeTest");
SOAPServiceMultiPortTypeTest service=new SOAPServiceMultiPortTypeTest(wsdl,sname);
DocLitBare b=service.getDocLitBarePort();
updateAddressPort(b,PORT);
BareDocumentResponse resp=b.testDocLitBare("CXF");
assertNotNull(resp);
assertEquals("CXF",resp.getCompany());
Greeter g=service.getGreeterPort();
updateAddressPort(g,PORT);
String result=g.greetMe("CXF");
assertEquals("Hello CXF",result);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testAsyncDiscardProxy() throws Exception {
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
assertNotNull(service);
Greeter greeter=service.getPort(portName,Greeter.class);
assertNotNull(service);
updateAddressPort(greeter,PORT);
Response r1=greeter.greetMeLaterAsync(3000);
greeter=null;
service=null;
System.gc();
System.gc();
System.gc();
assertEquals("Hello, finally!",r1.get().getResponseType());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testBasicAuth() throws Exception {
Service service=Service.create(serviceName);
service.addPort(fakePortName,"http://schemas.xmlsoap.org/soap/","http://localhost:" + PORT + "/SoapContext/SoapPort");
Greeter greeter=service.getPort(fakePortName,Greeter.class);
try {
BindingProvider bp=(BindingProvider)greeter;
bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY,"BJ");
bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY,"pswd");
String s=greeter.greetMe("secure");
assertEquals("Hello BJ",s);
bp.getRequestContext().remove(BindingProvider.USERNAME_PROPERTY);
bp.getRequestContext().remove(BindingProvider.PASSWORD_PROPERTY);
Client client=ClientProxy.getClient(greeter);
HTTPConduit httpConduit=(HTTPConduit)client.getConduit();
AuthorizationPolicy policy=new AuthorizationPolicy();
policy.setUserName("BJ2");
policy.setPassword("pswd");
httpConduit.setAuthorization(policy);
s=greeter.greetMe("secure");
assertEquals("Hello BJ2",s);
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testAddPortWithSpecifiedSoap11Binding() throws Exception {
Service service=Service.create(serviceName);
service.addPort(fakePortName,javax.xml.ws.soap.SOAPBinding.SOAP11HTTP_BINDING,"http://localhost:" + PORT + "/SoapContext/SoapPort");
Greeter greeter=service.getPort(fakePortName,Greeter.class);
String response=new String("Bonjour");
try {
greeter.greetMe("test");
String reply=greeter.sayHi();
assertNotNull("no response received from service",reply);
assertEquals(response,reply);
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testDynamicClientFactory() throws Exception {
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
String wsdlUrl=null;
wsdlUrl=wsdl.toURI().toString();
DynamicClientFactory dcf=DynamicClientFactory.newInstance();
Client client=dcf.createClient(wsdlUrl,serviceName,portName);
updateAddressPort(client,PORT);
client.invoke("greetMe","test");
Object[] result=client.invoke("sayHi");
assertNotNull("no response received from service",result);
assertEquals("Bonjour",result[0]);
Map jaxbContextProperties=new HashMap();
jaxbContextProperties.put("com.sun.xml.bind.defaultNamespaceRemap","uri:ultima:thule");
dcf.setJaxbContextProperties(jaxbContextProperties);
client=dcf.createClient(wsdlUrl,serviceName,portName);
updateAddressPort(client,PORT);
client.invoke("greetMe","test");
result=client.invoke("sayHi");
assertNotNull("no response received from service",result);
assertEquals("Bonjour",result[0]);
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testDocLitBareConnection() throws Exception {
SOAPServiceDocLitBare service=new SOAPServiceDocLitBare();
assertNotNull(service);
DocLitBare greeter=service.getPort(portName1,DocLitBare.class);
updateAddressPort(greeter,BARE_PORT);
try {
BareDocumentResponse bareres=greeter.testDocLitBare("MySimpleDocument");
assertNotNull("no response for operation testDocLitBare",bareres);
assertEquals("CXF",bareres.getCompany());
assertTrue(bareres.getId() == 1);
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testNillable() throws Exception {
SOAPService service=new SOAPService();
assertNotNull(service);
Greeter greeter=service.getPort(portName,Greeter.class);
updateAddressPort(greeter,PORT);
try {
String reply=greeter.testNillable("test",100);
assertEquals("test",reply);
reply=greeter.testNillable(null,100);
assertNull(reply);
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testServerAsync() throws Exception {
Service service=Service.create(serviceName);
service.addPort(fakePortName,javax.xml.ws.soap.SOAPBinding.SOAP11HTTP_BINDING,"http://localhost:" + PORT + "/SoapContext/AsyncSoapPort");
Greeter greeter=service.getPort(fakePortName,Greeter.class);
String resp=greeter.greetMe("World");
assertEquals("Hello World",resp);
}
InternalCallVerifier IdentityVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testAsyncCallUseProperAssignedExecutor() throws Exception {
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
class TestExecutor implements Executor {
private AtomicInteger count=new AtomicInteger();
public void execute( Runnable command){
int c=count.incrementAndGet();
LOG.info("asyn call time " + c);
command.run();
}
public int getCount(){
return count.get();
}
}
Executor executor=new TestExecutor();
service.setExecutor(executor);
assertNotNull(service);
assertSame(executor,service.getExecutor());
assertEquals(((TestExecutor)executor).getCount(),0);
Greeter greeter=service.getPort(portName,Greeter.class);
updateAddressPort(greeter,PORT);
List> responses=new ArrayList>();
for (int i=0; i < 5; i++) {
responses.add(greeter.greetMeAsync("asyn call" + i));
}
for ( Response resp : responses) {
resp.get();
}
assertEquals(5,((TestExecutor)executor).getCount());
}
APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testJaxWsDynamicClient() throws Exception {
URL wsdl=getClass().getResource("/wsdl/others/dynamic_client_base64.wsdl");
assertNotNull(wsdl);
String wsdlUrl=null;
wsdlUrl=wsdl.toURI().toString();
CXFBusFactory busFactory=new CXFBusFactory();
Bus bus=busFactory.createBus();
org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory dynamicClientFactory=org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory.newInstance(bus);
Client client=dynamicClientFactory.createClient(wsdlUrl);
assertNotNull(client);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetPortOneParam() throws Exception {
URL url=getClass().getResource("/wsdl/hello_world.wsdl");
Service service=Service.create(url,serviceName);
Greeter greeter=service.getPort(Greeter.class);
String response=new String("Bonjour");
try {
((BindingProvider)greeter).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"http://localhost:" + PORT + "/SoapContext/SoapPort");
greeter.greetMe("test");
String reply=greeter.sayHi();
assertNotNull("no response received from service",reply);
assertEquals(response,reply);
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
APIUtilityVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testAsyncSynchronousPolling() throws Exception {
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
assertNotNull(service);
final String expectedString=new String("Hello, finally!");
class Poller extends Thread {
Response response;
int tid;
Poller( Response r, int t){
response=r;
tid=t;
}
public void run(){
if (tid % 2 > 0) {
while (!response.isDone()) {
try {
Thread.sleep(100);
}
catch ( InterruptedException ex) {
}
}
}
GreetMeLaterResponse reply=null;
try {
reply=response.get();
}
catch ( Exception ex) {
fail("Poller " + tid + " failed with "+ ex);
}
assertNotNull("Poller " + tid + ": no response received from service",reply);
String s=reply.getResponseType();
assertEquals(expectedString,s);
}
}
Greeter greeter=service.getPort(portName,Greeter.class);
updateAddressPort(greeter,PORT);
long before=System.currentTimeMillis();
long delay=3000;
Response response=greeter.greetMeLaterAsync(delay);
long after=System.currentTimeMillis();
assertTrue("Duration of calls exceeded " + delay + " ms",after - before < delay);
assertFalse("Response already available.",response.isDone());
Poller[] pollers=new Poller[4];
for (int i=0; i < pollers.length; i++) {
pollers[i]=new Poller(response,i);
}
for ( Poller p : pollers) {
p.start();
}
for ( Poller p : pollers) {
p.join();
}
}
APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testBase64() throws Exception {
URL wsdl=getClass().getResource("/wsdl/others/dynamic_client_base64.wsdl");
assertNotNull(wsdl);
String wsdlUrl=null;
wsdlUrl=wsdl.toURI().toString();
CXFBusFactory busFactory=new CXFBusFactory();
Bus bus=busFactory.createBus();
DynamicClientFactory dynamicClientFactory=DynamicClientFactory.newInstance(bus);
Client client=dynamicClientFactory.createClient(wsdlUrl);
assertNotNull(client);
}
UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBogusAddress() throws Exception {
String realAddress="http://localhost:" + BOGUS_REAL_PORT + "/SoapContext/SoapPort";
SOAPServiceBogusAddressTest service=new SOAPServiceBogusAddressTest();
Greeter greeter=service.getSoapPort();
try {
greeter.greetMe("test");
fail("Should fail");
}
catch ( WebServiceException f) {
}
BindingProvider bp=(BindingProvider)greeter;
bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,realAddress);
greeter.greetMe("test");
greeter.greetMe("test");
bp.getRequestContext().remove(BindingProvider.ENDPOINT_ADDRESS_PROPERTY);
try {
greeter.greetMe("test");
fail("Should fail");
}
catch ( WebServiceException f) {
}
bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,realAddress);
String reply=greeter.sayHi();
assertNotNull("no response received from service",reply);
assertEquals("Bonjour",reply);
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testAsyncPollingCall() throws Exception {
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
assertNotNull(service);
Greeter greeter=service.getPort(portName,Greeter.class);
assertNotNull(service);
updateAddressPort(greeter,PORT);
long before=System.currentTimeMillis();
long delay=3000;
Response r1=greeter.greetMeLaterAsync(delay);
Response r2=greeter.greetMeLaterAsync(delay);
long after=System.currentTimeMillis();
assertTrue("Duration of calls exceeded " + (2 * delay) + " ms",after - before < (2 * delay));
assertFalse("Response already available.",r1.isDone());
assertFalse("Response already available.",r2.isDone());
long waited=0;
while (waited < (delay + 1000)) {
try {
Thread.sleep(500);
}
catch ( InterruptedException ex) {
}
if (r1.isDone() && r2.isDone()) {
break;
}
waited+=500;
}
assertTrue("Response is not available.",r1.isDone());
assertTrue("Response is not available.",r2.isDone());
}
IterativeVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBasicConnectionAndOneway() throws Exception {
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
assertNotNull(service);
Greeter greeter=service.getPort(portName,Greeter.class);
updateAddressPort(greeter,PORT);
String response1=new String("Hello Milestone-");
String response2=new String("Bonjour");
try {
for (int idx=0; idx < 1; idx++) {
String greeting=greeter.greetMe("Milestone-" + idx);
assertNotNull("no response received from service",greeting);
String exResponse=response1 + idx;
assertEquals(exResponse,greeting);
String reply=greeter.sayHi();
assertNotNull("no response received from service",reply);
assertEquals(response2,reply);
greeter.greetMeOneWay("Milestone-" + idx);
}
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBasicConnection() throws Exception {
SOAPService service=new SOAPService();
assertNotNull(service);
Greeter greeter=service.getPort(portName,Greeter.class);
updateAddressPort(greeter,PORT);
try {
greeter.greetMe("test");
String reply=greeter.sayHi();
assertNotNull("no response received from service",reply);
assertEquals("Bonjour",reply);
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
BindingProvider bp=(BindingProvider)greeter;
Map responseContext=bp.getResponseContext();
Integer responseCode=(Integer)responseContext.get(Message.RESPONSE_CODE);
assertEquals(200,responseCode.intValue());
}
APIUtilityVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testAsyncCallWithHandlerAndMultipleClients() throws Exception {
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
assertNotNull(service);
final MyHandler h=new MyHandler();
MyHandler.invocationCount=0;
final String expectedString=new String("Hello, finally!");
class Poller extends Thread {
Future> future;
int tid;
Poller( Future> f, int t){
future=f;
tid=t;
}
public void run(){
if (tid % 2 > 0) {
while (!future.isDone()) {
try {
Thread.sleep(100);
}
catch ( InterruptedException ex) {
ex.printStackTrace();
}
}
}
try {
future.get();
}
catch ( Exception ex) {
fail("Poller " + tid + " failed with "+ ex);
}
assertEquals("callback was not executed or did not return the expected result",expectedString,h.getReplyBuffer());
}
}
Greeter greeter=service.getPort(portName,Greeter.class);
updateAddressPort(greeter,PORT);
long before=System.currentTimeMillis();
long delay=3000;
Future> f=greeter.greetMeLaterAsync(delay,h);
long after=System.currentTimeMillis();
assertTrue("Duration of calls exceeded " + delay + " ms",after - before < delay);
assertFalse("Response already available.",f.isDone());
Poller[] pollers=new Poller[4];
for (int i=0; i < pollers.length; i++) {
pollers[i]=new Poller(f,i);
}
for ( Poller p : pollers) {
p.start();
}
for ( Poller p : pollers) {
p.join();
}
assertEquals(1,MyHandler.invocationCount);
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testAsyncCallWithHandler() throws Exception {
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
assertNotNull(service);
MyHandler h=new MyHandler();
MyHandler.invocationCount=0;
String expectedString=new String("Hello, finally!");
try {
Greeter greeter=service.getPort(portName,Greeter.class);
updateAddressPort(greeter,PORT);
long before=System.currentTimeMillis();
long delay=3000;
Future> f=greeter.greetMeLaterAsync(delay,h);
long after=System.currentTimeMillis();
assertTrue("Duration of calls exceeded " + delay + " ms",after - before < delay);
assertFalse("Response already available.",f.isDone());
int i=0;
while (!f.isDone() && i < 50) {
Thread.sleep(100);
i++;
}
assertEquals("callback was not executed or did not return the expected result",expectedString,h.getReplyBuffer());
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
assertEquals(1,MyHandler.invocationCount);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testAddPort() throws Exception {
Service service=Service.create(serviceName);
service.addPort(fakePortName,"http://schemas.xmlsoap.org/soap/","http://localhost:" + PORT + "/SoapContext/SoapPort");
Greeter greeter=service.getPort(fakePortName,Greeter.class);
String response=new String("Bonjour");
try {
greeter.greetMe("test");
String reply=greeter.sayHi();
assertNotNull("no response received from service",reply);
assertEquals(response,reply);
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
APIUtilityVerifier IterativeVerifier UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testFaults() throws Exception {
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
ExecutorService ex=Executors.newFixedThreadPool(1);
service.setExecutor(ex);
assertNotNull(service);
String noSuchCodeFault="NoSuchCodeLitFault";
String badRecordFault="BadRecordLitFault";
Greeter greeter=service.getPort(portName,Greeter.class);
updateAddressPort(greeter,PORT);
for (int idx=0; idx < 2; idx++) {
try {
greeter.testDocLitFault(noSuchCodeFault);
fail("Should have thrown NoSuchCodeLitFault exception");
}
catch ( NoSuchCodeLitFault nslf) {
assertNotNull(nslf.getFaultInfo());
assertNotNull(nslf.getFaultInfo().getCode());
}
try {
greeter.testDocLitFault(badRecordFault);
fail("Should have thrown BadRecordLitFault exception");
}
catch ( BadRecordLitFault brlf) {
BindingProvider bp=(BindingProvider)greeter;
Map responseContext=bp.getResponseContext();
String contentType=(String)responseContext.get(Message.CONTENT_TYPE);
assertEquals("text/xml;charset=utf-8",stripSpaces(contentType.toLowerCase()));
Integer responseCode=(Integer)responseContext.get(Message.RESPONSE_CODE);
assertEquals(500,responseCode.intValue());
assertNotNull(brlf.getFaultInfo());
assertEquals("BadRecordLitFault",brlf.getFaultInfo());
}
}
}
IterativeVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBasicConnection2() throws Exception {
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
assertNotNull(service);
Greeter greeter=service.getPort(Greeter.class);
((BindingProvider)greeter).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"http://localhost:" + PORT + "/SoapContext/SoapPort");
String response1=new String("Hello Milestone-");
String response2=new String("Bonjour");
try {
for (int idx=0; idx < 5; idx++) {
String greeting=greeter.greetMe("Milestone-" + idx);
assertNotNull("no response received from service",greeting);
String exResponse=response1 + idx;
assertEquals(exResponse,greeting);
String reply=greeter.sayHi();
assertNotNull("no response received from service",reply);
assertEquals(response2,reply);
greeter.greetMeOneWay("Milestone-" + idx);
}
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
Class: org.apache.cxf.systest.jaxws.ClientServerXMLTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testAddPort() throws Exception {
URL url=getClass().getResource("/wsdl/hello_world_xml_wrapped.wsdl");
Service service=Service.create(url,wrapServiceName);
assertNotNull(service);
service.addPort(wrapFakePortName,"http://cxf.apache.org/bindings/xformat","http://localhost:" + WRAP_PORT + "/XMLService/XMLPort");
String response1=new String("Hello ");
String response2=new String("Bonjour");
org.apache.hello_world_xml_http.wrapped.Greeter greeter=service.getPort(wrapPortName,org.apache.hello_world_xml_http.wrapped.Greeter.class);
updateAddressPort(greeter,WRAP_PORT);
try {
String username=System.getProperty("user.name");
String reply=greeter.greetMe(username);
assertNotNull("no response received from service",reply);
assertEquals(response1 + username,reply);
reply=greeter.sayHi();
assertNotNull("no response received from service",reply);
assertEquals(response2,reply);
BindingProvider bp=(BindingProvider)greeter;
Map responseContext=bp.getResponseContext();
Integer responseCode=(Integer)responseContext.get(Message.RESPONSE_CODE);
assertEquals(200,responseCode.intValue());
greeter.greetMeOneWay(System.getProperty("user.name"));
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testWrapBasicConnection() throws Exception {
org.apache.hello_world_xml_http.wrapped.XMLService service=new org.apache.hello_world_xml_http.wrapped.XMLService(this.getClass().getResource("/wsdl/hello_world_xml_wrapped.wsdl"),wrapServiceName);
assertNotNull(service);
String response1=new String("Hello ");
String response2=new String("Bonjour");
try {
org.apache.hello_world_xml_http.wrapped.Greeter greeter=service.getPort(wrapPortName,org.apache.hello_world_xml_http.wrapped.Greeter.class);
updateAddressPort(greeter,WRAP_PORT);
String username=System.getProperty("user.name");
String reply=greeter.greetMe(username);
assertNotNull("no response received from service",reply);
assertEquals(response1 + username,reply);
reply=greeter.sayHi();
assertNotNull("no response received from service",reply);
assertEquals(response2,reply);
greeter.greetMeOneWay(System.getProperty("user.name"));
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
APIUtilityVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testXMLFault() throws Exception {
org.apache.hello_world_xml_http.wrapped.XMLService service=new org.apache.hello_world_xml_http.wrapped.XMLService(this.getClass().getResource("/wsdl/hello_world_xml_wrapped.wsdl"),wrapServiceName);
assertNotNull(service);
org.apache.hello_world_xml_http.wrapped.Greeter greeter=service.getPort(wrapPortName,org.apache.hello_world_xml_http.wrapped.Greeter.class);
updateAddressPort(greeter,WRAP_PORT);
try {
greeter.pingMe();
fail("did not catch expected PingMeFault exception");
}
catch ( PingMeFault ex) {
assertEquals("minor value",1,ex.getFaultInfo().getMinor());
assertEquals("major value",2,ex.getFaultInfo().getMajor());
BindingProvider bp=(BindingProvider)greeter;
Map responseContext=bp.getResponseContext();
String contentType=(String)responseContext.get(Message.CONTENT_TYPE);
assertEquals("text/xml;charset=utf-8",stripSpaces(contentType.toLowerCase()));
Integer responseCode=(Integer)responseContext.get(Message.RESPONSE_CODE);
assertEquals(500,responseCode.intValue());
}
org.apache.hello_world_xml_http.wrapped.Greeter greeterFault=service.getXMLFaultPort();
updateAddressPort(greeterFault,REG_PORT);
try {
greeterFault.pingMe();
fail("did not catch expected runtime exception");
}
catch ( HTTPException ex) {
assertTrue("check expected message of exception",ex.getCause().getMessage().indexOf(GreeterFaultImpl.RUNTIME_EXCEPTION_MESSAGE) >= 0);
}
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testMixedConnection() throws Exception {
org.apache.hello_world_xml_http.mixed.XMLService service=new org.apache.hello_world_xml_http.mixed.XMLService(this.getClass().getResource("/wsdl/hello_world_xml_mixed.wsdl"),mixedServiceName);
assertNotNull(service);
String response1=new String("Hello ");
String response2=new String("Bonjour");
try {
org.apache.hello_world_xml_http.mixed.Greeter greeter=service.getPort(mixedPortName,org.apache.hello_world_xml_http.mixed.Greeter.class);
updateAddressPort(greeter,MIX_PORT);
String username=System.getProperty("user.name");
String reply=greeter.greetMe(username);
assertNotNull("no response received from service",reply);
assertEquals(response1 + username,reply);
SayHi request=new SayHi();
SayHiResponse response=greeter.sayHi1(request);
assertNotNull("no response received from service",response);
assertEquals(response2,response.getResponseType());
greeter.greetMeOneWay(System.getProperty("user.name"));
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBareBasicConnection() throws Exception {
XMLService service=new XMLService();
assertNotNull(service);
String response1="Hello ";
String response2="Bonjour";
try {
Greeter greeter=service.getPort(barePortName,Greeter.class);
updateAddressPort(greeter,REG_PORT);
String username=System.getProperty("user.name");
String reply=greeter.greetMe(username);
assertNotNull("no response received from service",reply);
assertEquals(response1 + username,reply);
reply=greeter.sayHi();
assertNotNull("no response received from service",reply);
assertEquals(response2,reply);
MyComplexStructType argument=new MyComplexStructType();
MyComplexStructType retVal=null;
String str1="this is element 1";
String str2="this is element 2";
int int1=42;
argument.setElem1(str1);
argument.setElem2(str2);
argument.setElem3(int1);
retVal=greeter.sendReceiveData(argument);
assertEquals(str1,retVal.getElem1());
assertEquals(str2,retVal.getElem2());
assertEquals(int1,retVal.getElem3());
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
Class: org.apache.cxf.systest.jaxws.JaxWsDynamicClientTest InternalCallVerifier EqualityVerifier
@Test public void testInvocation() throws Exception {
JaxWsDynamicClientFactory dcf=JaxWsDynamicClientFactory.newInstance();
URL wsdlURL=new URL("http://localhost:" + PORT + "/NoBodyParts/NoBodyPartsService?wsdl");
Client client=dcf.createClient(wsdlURL);
byte[] bucketOfBytes=IOUtils.readBytesFromStream(getClass().getResourceAsStream("/wsdl/no_body_parts.wsdl"));
Operation1 parameters=new Operation1();
parameters.setOptionString("opt-ion");
parameters.setTargetType("tar-get");
Object[] rparts=client.invoke("operation1",parameters,bucketOfBytes);
Operation1Response r=(Operation1Response)rparts[0];
assertEquals(md5(bucketOfBytes),r.getStatus());
ClientCallback callback=new ClientCallback();
client.invoke(callback,"operation1",parameters,bucketOfBytes);
rparts=callback.get();
r=(Operation1Response)rparts[0];
assertEquals(md5(bucketOfBytes),r.getStatus());
}
Class: org.apache.cxf.systest.jaxws.JaxwsAsyncFailOverTest BooleanVerifier InternalCallVerifier
@Test public void testUseFailOverOnClient() throws Exception {
List serviceList=new ArrayList();
serviceList.add("http://localhost:" + PORT + "/SoapContext/GreeterPort");
RandomStrategy strategy=new RandomStrategy();
strategy.setAlternateAddresses(serviceList);
FailoverFeature ff=new FailoverFeature();
ff.setStrategy(strategy);
JaxWsProxyFactoryBean factory=new JaxWsProxyFactoryBean();
factory.setAddress("http://localhost:" + PORT2 + "/SoapContext/GreeterPort");
factory.getFeatures().add(ff);
factory.setServiceClass(Greeter.class);
Greeter proxy=factory.create(Greeter.class);
Response response=proxy.greetMeAsync("cxf");
int waitCount=0;
while (!response.isDone() && waitCount < 15) {
Thread.sleep(1000);
waitCount++;
}
assertTrue("Response still not received.",response.isDone());
}
Class: org.apache.cxf.systest.jaxws.JaxwsExecutorTest BooleanVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testUseCustomExecutorOnClient() throws Exception {
BasicGreeterService service=new BasicGreeterService();
class CustomExecutor implements Executor {
private int count;
public void execute( Runnable command){
count++;
command.run();
}
public int getCount(){
return count;
}
}
CustomExecutor executor=new CustomExecutor();
service.setExecutor(executor);
assertSame(executor,service.getExecutor());
Greeter proxy=service.getGreeterPort();
updateAddressPort(proxy,PORT);
assertEquals(0,executor.getCount());
Response response=proxy.greetMeAsync("cxf");
int waitCount=0;
while (!response.isDone() && waitCount < 15) {
Thread.sleep(1000);
waitCount++;
}
assertTrue("Response still not received.",response.isDone());
assertEquals(1,executor.getCount());
}
Class: org.apache.cxf.systest.jaxws.LocatorClientServerTest APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testLookupEndpointAndVerifyWsdlLocationOnly() throws Exception {
URL wsdl=getClass().getResource("/wsdl/locator.wsdl");
assertNotNull(wsdl);
LocatorService_Service ss=new LocatorService_Service(wsdl,serviceName);
LocatorService port=ss.getLocatorServicePort();
updateAddressPort(port,PORT);
W3CEndpointReference epr=port.lookupEndpoint(new QName("http://service/2","Number"));
String eprString=epr.toString();
assertTrue(eprString.contains("Metadata"));
System.out.println(eprString);
assertTrue(eprString.contains("wsdlLocation=\"wsdlLoc\""));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testLookupEndpointAndVerifyWsdlLocationAndNamespace() throws Exception {
URL wsdl=getClass().getResource("/wsdl/locator.wsdl");
assertNotNull(wsdl);
LocatorService_Service ss=new LocatorService_Service(wsdl,serviceName);
LocatorService port=ss.getLocatorServicePort();
updateAddressPort(port,PORT);
W3CEndpointReference epr=port.lookupEndpoint(new QName("http://service/1","Number"));
String eprString=epr.toString();
assertTrue(eprString.contains("Metadata"));
assertTrue(eprString.contains("wsdlLocation=\"http://service/1 wsdlLoc\""));
}
Class: org.apache.cxf.systest.jaxws.OASISCatalogTest UtilityVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testClientWithoutCatalog() throws Exception {
URL wsdl=getClass().getResource("/wsdl/catalog/hello_world_services.wsdl");
assertNotNull(wsdl);
Bus bus=BusFactory.getDefaultBus();
OASISCatalogManager catalog=new OASISCatalogManager();
bus.setExtension(catalog,OASISCatalogManager.class);
WSDLManagerImpl mgr=(WSDLManagerImpl)bus.getExtension(WSDLManager.class);
mgr.setDisableSchemaCache(true);
try {
SOAPService service=new SOAPService(wsdl,serviceName);
service.getPort(portName,Greeter.class);
fail("Test did not fail as expected");
}
catch ( WebServiceException e) {
}
Enumeration jaxwscatalog=getClass().getClassLoader().getResources("META-INF/jax-ws-catalog.xml");
assertNotNull(jaxwscatalog);
while (jaxwscatalog.hasMoreElements()) {
URL url=jaxwscatalog.nextElement();
catalog.loadCatalog(url);
}
SOAPService service=new SOAPService(wsdl,serviceName);
Greeter greeter=service.getPort(portName,Greeter.class);
assertNotNull(greeter);
bus.shutdown(true);
}
InternalCallVerifier NullVerifier
@Test public void testClientWithDefaultCatalog() throws Exception {
URL wsdl=getClass().getResource("/wsdl/catalog/hello_world_services.wsdl");
assertNotNull(wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
assertNotNull(service);
Greeter greeter=service.getPort(portName,Greeter.class);
assertNotNull(greeter);
}
Class: org.apache.cxf.systest.jaxws.SchemaValidationClientServerTest BranchVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSchemaValidationWithMultipleXsds() throws Exception {
Service service=new Service();
assertNotNull(service);
try (ServicePortType greeter=service.getPort(portName,ServicePortType.class)){
greeter.getInInterceptors().add(new LoggingInInterceptor());
greeter.getOutInterceptors().add(new LoggingOutInterceptor());
updateAddressPort(greeter,PORT);
RequestIdType requestId=new RequestIdType();
requestId.setId("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee");
CkRequestType request=new CkRequestType();
request.setRequest(requestId);
greeter.getRequestContext().put(Message.SCHEMA_VALIDATION_ENABLED,Boolean.TRUE);
RequestHeader header=new RequestHeader();
header.setHeaderValue("AABBCC");
CkResponseType response=greeter.ckR(request,header);
assertEquals(response.getProduct().get(0).getAction().getStatus(),4);
try {
requestId.setId("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeeez");
request.setRequest(requestId);
greeter.ckR(request,header);
fail("should catch marshall exception as the invalid outgoing message per schema");
}
catch ( Exception e) {
assertTrue(e.getMessage().contains("Marshalling Error"));
boolean english="en".equals(java.util.Locale.getDefault().getLanguage());
if (english) {
assertTrue(e.getMessage().contains("is not facet-valid with respect to pattern"));
}
}
try {
requestId.setId("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee");
request.setRequest(requestId);
header.setHeaderValue("AABBCCDDEEFFGGHHIIJJ");
greeter.ckR(request,header);
fail("should catch marshall exception as the invalid outgoing message per schema");
}
catch ( Exception e) {
assertTrue(e.getMessage().contains("Marshalling Error"));
boolean english="en".equals(java.util.Locale.getDefault().getLanguage());
if (english) {
assertTrue(e.getMessage().contains("is not facet-valid with respect to maxLength"));
}
}
try {
requestId.setId("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee");
request.setRequest(requestId);
header.setHeaderValue("AABBCCDDEEFFGGHHIIJJ");
greeter.getRequestContext().put(Message.SCHEMA_VALIDATION_ENABLED,Boolean.FALSE);
greeter.ckR(request,header);
fail("should catch marshall exception as the invalid outgoing message per schema");
}
catch ( Exception e) {
assertTrue(e.getMessage().contains("Could not validate soapheader "));
boolean english="en".equals(java.util.Locale.getDefault().getLanguage());
if (english) {
assertTrue(e.getMessage().contains("is not facet-valid with respect to maxLength"));
}
}
}
}
Class: org.apache.cxf.systest.jaxws.WsdlGetUtilsTest BooleanVerifier InternalCallVerifier
@Test public void testNewDocumentIsCreatedForEachWsdlRequest(){
JaxWsServerFactoryBean factory=new JaxWsServerFactoryBean();
factory.setServiceBean(new StuffImpl());
factory.setAddress("http://localhost:" + PORT + "/Stuff");
Server server=factory.create();
try {
Message message=new MessageImpl();
Exchange exchange=new ExchangeImpl();
exchange.put(Bus.class,getBus());
exchange.put(Service.class,server.getEndpoint().getService());
exchange.put(Endpoint.class,server.getEndpoint());
message.setExchange(exchange);
Map map=UrlUtils.parseQueryString("wsdl");
String baseUri="http://localhost:" + PORT + "/Stuff";
String ctx="/Stuff";
WSDLGetUtils utils=new WSDLGetUtils();
Document doc=utils.getDocument(message,baseUri,map,ctx,server.getEndpoint().getEndpointInfo());
Document doc2=utils.getDocument(message,baseUri,map,ctx,server.getEndpoint().getEndpointInfo());
assertFalse(doc == doc2);
}
finally {
server.stop();
}
}
Class: org.apache.cxf.systest.jaxws.beanpostprocessor.BeanPostProcessorTest InternalCallVerifier EqualityVerifier
@Test public void verifyServices() throws Exception {
JaxWsClientFactoryBean cf=new JaxWsClientFactoryBean();
cf.setAddress("local://services/Alger");
cf.setServiceClass(IWebServiceRUs.class);
Client client=cf.create();
String response=(String)client.invoke("consultTheOracle")[0];
assertEquals("All your bases belong to us.",response);
Service service=WebServiceRUs.getService();
assertEquals(JAXBDataBinding.class,service.getDataBinding().getClass());
}
Class: org.apache.cxf.systest.jaxws.beanpostprocessor.CustomizedfBeanPostProcessorTest BooleanVerifier InternalCallVerifier
@Test public void verifyServices() throws Exception {
JaxWsWebServicePublisherBeanPostProcessor bpp=(JaxWsWebServicePublisherBeanPostProcessor)applicationContext.getBean("postprocess");
assertTrue(bpp.isCustomizedDataBinding());
assertTrue(bpp.isCustomizedServerFactory());
}
Class: org.apache.cxf.systest.jaxws.tracing.htrace.HTraceTracingTest APIUtilityVerifier InternalCallVerifier ConditionMatcher
@Test public void testThatNewSpanIsCreatedWhenNotProvided() throws MalformedURLException {
final BookStoreService service=createJaxWsService();
assertThat(service.getBooks().size(),equalTo(2));
assertThat(TestSpanReceiver.getAllSpans().size(),equalTo(2));
assertThat(TestSpanReceiver.getAllSpans().get(0).getDescription(),equalTo("Get Books"));
assertThat(TestSpanReceiver.getAllSpans().get(1).getDescription(),equalTo("POST /BookStore"));
final Map> response=getResponseHeaders(service);
assertThat(response.get(TracerHeaders.DEFAULT_HEADER_SPAN_ID),nullValue());
}
APIUtilityVerifier InternalCallVerifier ConditionMatcher
@Test public void testThatProvidedSpanIsNotClosedWhenActive() throws MalformedURLException {
final Tracer tracer=createTracer();
final BookStoreService service=createJaxWsService(new Configurator(){
@Override public void configure( final JaxWsProxyFactoryBean factory){
factory.getOutInterceptors().add(new HTraceClientStartInterceptor(tracer));
factory.getInInterceptors().add(new HTraceClientStopInterceptor());
}
}
);
try (final TraceScope scope=tracer.newScope("test span")){
assertThat(service.getBooks().size(),equalTo(2));
assertThat(Tracer.getCurrentSpan(),not(nullValue()));
assertThat(TestSpanReceiver.getAllSpans().size(),equalTo(2));
assertThat(TestSpanReceiver.getAllSpans().get(0).getDescription(),equalTo("Get Books"));
assertThat(TestSpanReceiver.getAllSpans().get(0).getParents().length,equalTo(1));
assertThat(TestSpanReceiver.getAllSpans().get(1).getDescription(),equalTo("POST /BookStore"));
}
assertThat(TestSpanReceiver.getAllSpans().size(),equalTo(3));
assertThat(TestSpanReceiver.getAllSpans().get(2).getDescription(),equalTo("test span"));
final Map> response=getResponseHeaders(service);
assertThat(response.get(TracerHeaders.DEFAULT_HEADER_SPAN_ID),not(nullValue()));
}
APIUtilityVerifier InternalCallVerifier ConditionMatcher
@Test public void testThatNewChildSpanIsCreatedWhenParentIsProvided() throws MalformedURLException {
final Tracer tracer=createTracer();
final BookStoreService service=createJaxWsService(new Configurator(){
@Override public void configure( final JaxWsProxyFactoryBean factory){
factory.getOutInterceptors().add(new HTraceClientStartInterceptor(tracer));
factory.getInInterceptors().add(new HTraceClientStopInterceptor());
}
}
);
assertThat(service.getBooks().size(),equalTo(2));
assertThat(TestSpanReceiver.getAllSpans().size(),equalTo(3));
assertThat(TestSpanReceiver.getAllSpans().get(0).getDescription(),equalTo("Get Books"));
assertThat(TestSpanReceiver.getAllSpans().get(0).getParents().length,equalTo(1));
assertThat(TestSpanReceiver.getAllSpans().get(1).getDescription(),equalTo("POST /BookStore"));
assertThat(TestSpanReceiver.getAllSpans().get(2).getDescription(),equalTo("POST http://localhost:" + PORT + "/BookStore"));
final Map> response=getResponseHeaders(service);
assertThat(response.get(TracerHeaders.DEFAULT_HEADER_SPAN_ID),not(nullValue()));
}
APIUtilityVerifier InternalCallVerifier ConditionMatcher
@Test public void testThatNewInnerSpanIsCreated() throws MalformedURLException {
final SpanId spanId=SpanId.fromRandom();
final Map> headers=new HashMap>();
headers.put(TracerHeaders.DEFAULT_HEADER_SPAN_ID,Arrays.asList(spanId.toString()));
final BookStoreService service=createJaxWsService(headers);
assertThat(service.getBooks().size(),equalTo(2));
assertThat(TestSpanReceiver.getAllSpans().size(),equalTo(2));
assertThat(TestSpanReceiver.getAllSpans().get(0).getDescription(),equalTo("Get Books"));
assertThat(TestSpanReceiver.getAllSpans().get(1).getDescription(),equalTo("POST /BookStore"));
final Map> response=getResponseHeaders(service);
assertThat(response.get(TracerHeaders.DEFAULT_HEADER_SPAN_ID),hasItems(spanId.toString()));
}
Class: org.apache.cxf.systest.jaxws.websocket.ClientServerWebSocketTest APIUtilityVerifier IterativeVerifier UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testFaults() throws Exception {
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
ExecutorService ex=Executors.newFixedThreadPool(1);
service.setExecutor(ex);
assertNotNull(service);
String noSuchCodeFault="NoSuchCodeLitFault";
String badRecordFault="BadRecordLitFault";
Greeter greeter=service.getPort(portName,Greeter.class);
updateGreeterAddress(greeter,PORT);
for (int idx=0; idx < 2; idx++) {
try {
greeter.testDocLitFault(noSuchCodeFault);
fail("Should have thrown NoSuchCodeLitFault exception");
}
catch ( NoSuchCodeLitFault nslf) {
assertNotNull(nslf.getFaultInfo());
assertNotNull(nslf.getFaultInfo().getCode());
}
try {
greeter.testDocLitFault(badRecordFault);
fail("Should have thrown BadRecordLitFault exception");
}
catch ( BadRecordLitFault brlf) {
BindingProvider bp=(BindingProvider)greeter;
Map responseContext=bp.getResponseContext();
String contentType=(String)responseContext.get(Message.CONTENT_TYPE);
assertEquals("text/xml; charset=utf-8",contentType.toLowerCase());
Integer responseCode=(Integer)responseContext.get(Message.RESPONSE_CODE);
assertEquals(500,responseCode.intValue());
assertNotNull(brlf.getFaultInfo());
assertEquals("BadRecordLitFault",brlf.getFaultInfo());
}
}
}
IterativeVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBasicConnectionAndOneway() throws Exception {
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
Greeter greeter=service.getPort(portName,Greeter.class);
updateGreeterAddress(greeter,PORT);
String response1=new String("Hello Milestone-");
String response2=new String("Bonjour");
try {
for (int idx=0; idx < 1; idx++) {
String greeting=greeter.greetMe("Milestone-" + idx);
assertNotNull("no response received from service",greeting);
String exResponse=response1 + idx;
assertEquals(exResponse,greeting);
String reply=greeter.sayHi();
assertNotNull("no response received from service",reply);
assertEquals(response2,reply);
greeter.greetMeOneWay("Milestone-" + idx);
}
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
IterativeVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBasicConnection2() throws Exception {
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
Greeter greeter=service.getPort(Greeter.class);
updateGreeterAddress(greeter,PORT);
String response1=new String("Hello Milestone-");
String response2=new String("Bonjour");
try {
for (int idx=0; idx < 5; idx++) {
String greeting=greeter.greetMe("Milestone-" + idx);
assertNotNull("no response received from service",greeting);
String exResponse=response1 + idx;
assertEquals(exResponse,greeting);
String reply=greeter.sayHi();
assertNotNull("no response received from service",reply);
assertEquals(response2,reply);
greeter.greetMeOneWay("Milestone-" + idx);
}
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
APIUtilityVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testAsyncSynchronousPolling() throws Exception {
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
assertNotNull(service);
final String expectedString=new String("Hello, finally!");
class Poller extends Thread {
Response response;
int tid;
Poller( Response r, int t){
response=r;
tid=t;
}
public void run(){
if (tid % 2 > 0) {
while (!response.isDone()) {
try {
Thread.sleep(100);
}
catch ( InterruptedException ex) {
}
}
}
GreetMeLaterResponse reply=null;
try {
reply=response.get();
}
catch ( Exception ex) {
fail("Poller " + tid + " failed with "+ ex);
}
assertNotNull("Poller " + tid + ": no response received from service",reply);
String s=reply.getResponseType();
assertEquals(expectedString,s);
}
}
Greeter greeter=service.getPort(portName,Greeter.class);
updateGreeterAddress(greeter,PORT);
long before=System.currentTimeMillis();
long delay=3000;
Response response=greeter.greetMeLaterAsync(delay);
long after=System.currentTimeMillis();
assertTrue("Duration of calls exceeded " + delay + " ms",after - before < delay);
assertFalse("Response already available.",response.isDone());
Poller[] pollers=new Poller[4];
for (int i=0; i < pollers.length; i++) {
pollers[i]=new Poller(response,i);
}
for ( Poller p : pollers) {
p.start();
}
for ( Poller p : pollers) {
p.join();
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBasicConnection() throws Exception {
SOAPService service=new SOAPService();
Greeter greeter=service.getPort(portName,Greeter.class);
updateGreeterAddress(greeter,PORT);
try {
String reply=greeter.greetMe("test");
assertNotNull("no response received from service",reply);
assertEquals("Hello test",reply);
reply=greeter.sayHi();
assertNotNull("no response received from service",reply);
assertEquals("Bonjour",reply);
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
BindingProvider bp=(BindingProvider)greeter;
Map responseContext=bp.getResponseContext();
Integer responseCode=(Integer)responseContext.get(Message.RESPONSE_CODE);
assertEquals(200,responseCode.intValue());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test @org.junit.Ignore public void testBasicAuth() throws Exception {
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
Greeter greeter=service.getPort(portName,Greeter.class);
updateGreeterAddress(greeter,PORT);
try {
BindingProvider bp=(BindingProvider)greeter;
bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY,"BJ");
bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY,"pswd");
String s=greeter.greetMe("secure");
assertEquals("Hello BJ",s);
bp.getRequestContext().remove(BindingProvider.USERNAME_PROPERTY);
bp.getRequestContext().remove(BindingProvider.PASSWORD_PROPERTY);
Client client=ClientProxy.getClient(greeter);
HTTPConduit httpConduit=(HTTPConduit)client.getConduit();
AuthorizationPolicy policy=new AuthorizationPolicy();
policy.setUserName("BJ2");
policy.setPassword("pswd");
httpConduit.setAuthorization(policy);
s=greeter.greetMe("secure");
assertEquals("Hello BJ2",s);
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testAsyncPollingCall() throws Exception {
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
Greeter greeter=service.getPort(portName,Greeter.class);
updateGreeterAddress(greeter,PORT);
long before=System.currentTimeMillis();
long delay=3000;
Response r1=greeter.greetMeLaterAsync(delay);
Response r2=greeter.greetMeLaterAsync(delay);
long after=System.currentTimeMillis();
assertTrue("Duration of calls exceeded " + (2 * delay) + " ms",after - before < (2 * delay));
assertFalse("Response already available.",r1.isDone());
assertFalse("Response already available.",r2.isDone());
long waited=0;
while (waited < (delay + 1000)) {
try {
Thread.sleep(500);
}
catch ( InterruptedException ex) {
}
if (r1.isDone() && r2.isDone()) {
break;
}
waited+=500;
}
assertTrue("Response is not available.",r1.isDone());
assertTrue("Response is not available.",r2.isDone());
}
Class: org.apache.cxf.systest.jibx.ClientServerJibxTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCallFromDocLitBareClient() throws Exception {
SpringBusFactory factory=new SpringBusFactory();
Bus bus=factory.createBus("org/apache/cxf/systest/jibx/cxf.xml");
BusFactory.setDefaultBus(bus);
URL wsdl=this.getClass().getResource("/wsdl_systest_databinding/jibx/doc_lit_bare.wsdl");
assertNotNull("We should have found the WSDL here. ",wsdl);
org.apache.cxf.jibx.doc_lit_bare.SOAPService ss=new org.apache.cxf.jibx.doc_lit_bare.SOAPService(wsdl,DOC_LIT_BARE_SERVICE);
PutLastTradedPricePortType port=ss.getSoapPort();
updateAddressPort(port,WSDL_PORT);
ClientProxy.getClient(port).getInInterceptors().add(new LoggingInInterceptor());
ClientProxy.getClient(port).getOutInterceptors().add(new LoggingOutInterceptor());
StringRespType resp=port.bareNoParam();
assertEquals("Get a wrong response","Get the request!",resp.getStringRespType());
InDecimal xd=new InDecimal();
xd.setInDecimal(new BigDecimal(123));
OutString response=port.nillableParameter(xd);
assertEquals("Get a wrong response","Get the request 123",response.getOutString());
In data=new In();
data.setTickerPrice(12.33F);
data.setTickerSymbol("CXF");
port.putLastTradedPrice(data);
Inout dataio=new Inout();
dataio.setTickerPrice(12.33F);
dataio.setTickerSymbol("CXF");
Holder holder=new Holder(dataio);
port.sayHi(holder);
assertEquals("Get a wrong response","BAK",holder.value.getTickerSymbol());
}
UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCallFromClient() throws Exception {
SpringBusFactory factory=new SpringBusFactory();
Bus bus=factory.createBus("org/apache/cxf/systest/jibx/cxf.xml");
BusFactory.setDefaultBus(bus);
URL wsdl=this.getClass().getResource("/wsdl_systest_databinding/jibx/hello_world.wsdl");
assertNotNull("We should have found the WSDL here. ",wsdl);
SOAPService ss=new SOAPService(wsdl,SERVICE_NAME);
Greeter port=ss.getSoapPort();
updateAddressPort(port,WSDL_PORT);
String resp;
ClientProxy.getClient(port).getInInterceptors().add(new LoggingInInterceptor());
ClientProxy.getClient(port).getOutInterceptors().add(new LoggingOutInterceptor());
resp=port.sayHi();
assertEquals("We should get the right response","Bonjour",resp);
resp=port.greetMe("Willem");
assertEquals("We should get the right response","Hello Willem",resp);
try {
port.greetMe("fault");
fail("Should have been a fault");
}
catch ( GreetMeFault ex) {
assertEquals("Some fault detail",ex.getFaultInfo().getGreetMeFaultDetail());
}
try {
port.pingMe();
fail("We expect exception here");
}
catch ( PingMeFault ex) {
FaultDetail detail=ex.getFaultInfo();
assertEquals("Wrong faultDetail major",detail.getMajor(),2);
assertEquals("Wrong faultDetail minor",detail.getMinor(),1);
}
}
Class: org.apache.cxf.systest.jms.JMSClientServerSoap12Test IterativeVerifier UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGzipEncodingWithJms() throws Exception {
QName serviceName=new QName("http://apache.org/hello_world_doc_lit","SOAPService8");
QName portName=new QName("http://apache.org/hello_world_doc_lit","SoapPort8");
URL wsdl=getWSDLURL("/wsdl/hello_world_doc_lit.wsdl");
SOAPService2 service=new SOAPService2(wsdl,serviceName);
Greeter greeter=markForClose(service.getPort(portName,Greeter.class,cff));
for (int idx=0; idx < 5; idx++) {
greeter.greetMeOneWay("test String");
String greeting=greeter.greetMe("Milestone-" + idx);
Assert.assertEquals(new String("Hello Milestone-") + idx,greeting);
String reply=greeter.sayHi();
Assert.assertEquals("Bonjour",reply);
try {
greeter.pingMe();
Assert.fail("Should have thrown FaultException");
}
catch ( PingMeFault ex) {
Assert.assertNotNull(ex.getFaultInfo());
}
}
}
IterativeVerifier UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testWSAddressingWithJms() throws Exception {
QName serviceName=new QName("http://apache.org/hello_world_doc_lit","SOAPService8");
QName portName=new QName("http://apache.org/hello_world_doc_lit","SoapPort8");
URL wsdl=getWSDLURL("/wsdl/hello_world_doc_lit.wsdl");
SOAPService2 service=new SOAPService2(wsdl,serviceName);
Greeter greeter=markForClose(service.getPort(portName,Greeter.class,cff,new AddressingFeature()));
for (int idx=0; idx < 5; idx++) {
greeter.greetMeOneWay("test String");
String greeting=greeter.greetMe("Milestone-" + idx);
Assert.assertEquals(new String("Hello Milestone-") + idx,greeting);
String reply=greeter.sayHi();
Assert.assertEquals("Bonjour",reply);
try {
greeter.pingMe();
Assert.fail("Should have thrown FaultException");
}
catch ( PingMeFault ex) {
Assert.assertNotNull(ex.getFaultInfo());
}
}
}
Class: org.apache.cxf.systest.jms.JMSClientServerTest InternalCallVerifier EqualityVerifier
@Test public void testReplyToConfig() throws Exception {
ActiveMQConnectionFactory cf=new ActiveMQConnectionFactory(broker.getBrokerURL());
TestReceiver receiver=new TestReceiver(cf,"SoapService7.replyto.queue",false);
receiver.setStaticReplyQueue("SoapService7.reply.queue");
receiver.runAsync();
QName serviceName=new QName("http://apache.org/hello_world_doc_lit","SOAPService7");
QName portName=new QName("http://apache.org/hello_world_doc_lit","SoapPort7");
URL wsdl=getWSDLURL("/wsdl/hello_world_doc_lit.wsdl");
SOAPService7 service=new SOAPService7(wsdl,serviceName);
Greeter greeter=service.getPort(portName,Greeter.class);
String name="FooBar";
String reply=greeter.greetMe(name);
Assert.assertEquals("Hello " + name,reply);
((Closeable)greeter).close();
}
IterativeVerifier UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void docBasicJmsDestinationTest() throws Exception {
QName serviceName=new QName("http://apache.org/hello_world_doc_lit","SOAPService6");
QName portName=new QName("http://apache.org/hello_world_doc_lit","SoapPort6");
URL wsdl=getWSDLURL("/wsdl/hello_world_doc_lit.wsdl");
SOAPService2 service=new SOAPService2(wsdl,serviceName);
Greeter greeter=service.getPort(portName,Greeter.class);
for (int idx=0; idx < 5; idx++) {
greeter.greetMeOneWay("test String");
String greeting=greeter.greetMe("Milestone-" + idx);
assertEquals("Hello Milestone-" + idx,greeting);
String reply=greeter.sayHi();
assertEquals("Bonjour",reply);
try {
greeter.pingMe();
fail("Should have thrown FaultException");
}
catch ( PingMeFault ex) {
assertNotNull(ex.getFaultInfo());
}
}
((java.io.Closeable)greeter).close();
}
BranchVerifier UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testQueueOneWaySpecCompliantConnection() throws Throwable {
QName serviceName=new QName("http://cxf.apache.org/hello_world_jms","HelloWorldQueueDecoupledOneWaysService");
QName portName=new QName("http://cxf.apache.org/hello_world_jms","HelloWorldQueueDecoupledOneWaysPort");
URL wsdl=getWSDLURL("/wsdl/jms_test.wsdl");
assertNotNull(wsdl);
String wsdlString2="testutils/jms_test.wsdl";
wsdlStrings.add(wsdlString2);
broker.updateWsdl(getBus(),wsdlString2);
HelloWorldQueueDecoupledOneWaysService service=new HelloWorldQueueDecoupledOneWaysService(wsdl,serviceName);
assertNotNull(service);
Endpoint requestEndpoint=null;
HelloWorldOneWayPort greeter=service.getPort(portName,HelloWorldOneWayPort.class);
try {
GreeterImplQueueDecoupledOneWays requestServant=new GreeterImplQueueDecoupledOneWays(true);
requestEndpoint=Endpoint.publish(null,requestServant);
BindingProvider bp=(BindingProvider)greeter;
Map requestContext=bp.getRequestContext();
JMSMessageHeadersType requestHeader=new JMSMessageHeadersType();
requestHeader.setJMSReplyTo("dynamicQueues/test.jmstransport.oneway.with.set.replyto.reply");
requestContext.put(JMSConstants.JMS_CLIENT_REQUEST_HEADERS,requestHeader);
String expectedRequest="JMS:Queue:Request";
greeter.greetMeOneWay(expectedRequest);
String request=requestServant.ackRequestReceived(5000);
if (request == null) {
if (requestServant.getException() != null) {
fail(requestServant.getException().getMessage());
}
else {
fail("The oneway call didn't reach its intended endpoint");
}
}
assertEquals(expectedRequest,request);
requestServant.proceedWithReply();
boolean ack=requestServant.ackNoReplySent(5000);
if (!ack) {
if (requestServant.getException() != null) {
throw requestServant.getException();
}
else {
fail("The decoupled one-way reply was sent");
}
}
}
catch ( Exception ex) {
throw ex;
}
finally {
if (requestEndpoint != null) {
requestEndpoint.stop();
}
((java.io.Closeable)greeter).close();
}
}
BranchVerifier UtilityVerifier InternalCallVerifier EqualityVerifier IgnoredMethod HybridVerifier
@Test @Ignore public void testQueueDecoupledOneWaysConnection() throws Exception {
QName serviceName=new QName("http://cxf.apache.org/hello_world_jms","HelloWorldQueueDecoupledOneWaysService");
QName portName=new QName("http://cxf.apache.org/hello_world_jms","HelloWorldQueueDecoupledOneWaysPort");
URL wsdl=getWSDLURL("/wsdl/jms_test.wsdl");
String wsdl2="testutils/jms_test.wsdl".intern();
wsdlStrings.add(wsdl2);
broker.updateWsdl(getBus(),wsdl2);
HelloWorldQueueDecoupledOneWaysService service=new HelloWorldQueueDecoupledOneWaysService(wsdl,serviceName);
Endpoint requestEndpoint=null;
Endpoint replyEndpoint=null;
HelloWorldOneWayPort greeter=service.getPort(portName,HelloWorldOneWayPort.class);
try {
GreeterImplQueueDecoupledOneWays requestServant=new GreeterImplQueueDecoupledOneWays();
requestEndpoint=Endpoint.publish("",requestServant);
GreeterImplQueueDecoupledOneWaysDeferredReply replyServant=new GreeterImplQueueDecoupledOneWaysDeferredReply();
replyEndpoint=Endpoint.publish("",replyServant);
BindingProvider bp=(BindingProvider)greeter;
Map requestContext=bp.getRequestContext();
JMSMessageHeadersType requestHeader=new JMSMessageHeadersType();
requestHeader.setJMSReplyTo("dynamicQueues/test.jmstransport.oneway.with.set.replyto.reply");
requestContext.put(JMSConstants.JMS_CLIENT_REQUEST_HEADERS,requestHeader);
String expectedRequest="JMS:Queue:Request";
greeter.greetMeOneWay(expectedRequest);
String request=requestServant.ackRequestReceived(5000);
if (request == null) {
if (requestServant.getException() != null) {
fail(requestServant.getException().getMessage());
}
else {
fail("The oneway call didn't reach its intended endpoint");
}
}
assertEquals(expectedRequest,request);
requestServant.proceedWithReply();
String expectedReply=requestServant.ackReplySent(5000);
if (expectedReply == null) {
if (requestServant.getException() != null) {
fail(requestServant.getException().getMessage());
}
else {
fail("The decoupled one-way reply was not sent");
}
}
String reply=replyServant.ackRequest(5000);
if (reply == null) {
if (replyServant.getException() != null) {
fail(replyServant.getException().getMessage());
}
else {
fail("The decoupled one-way reply didn't reach its intended endpoint");
}
}
assertEquals(expectedReply,reply);
}
catch ( Exception ex) {
throw ex;
}
finally {
if (requestEndpoint != null) {
requestEndpoint.stop();
}
if (replyEndpoint != null) {
replyEndpoint.stop();
}
((java.io.Closeable)greeter).close();
}
}
IterativeVerifier UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBasicConnection() throws Exception {
QName serviceName=new QName("http://cxf.apache.org/hello_world_jms","HelloWorldService");
QName portName=new QName("http://cxf.apache.org/hello_world_jms","HelloWorldPort");
URL wsdl=getWSDLURL("/wsdl/jms_test.wsdl");
HelloWorldService service=new HelloWorldService(wsdl,serviceName);
String response1=new String("Hello Milestone-");
String response2=new String("Bonjour");
HelloWorldPortType greeter=service.getPort(portName,HelloWorldPortType.class);
for (int idx=0; idx < 5; idx++) {
String greeting=greeter.greetMe("Milestone-" + idx);
assertNotNull("no response received from service",greeting);
String exResponse=response1 + idx;
assertEquals(exResponse,greeting);
String reply=greeter.sayHi();
assertNotNull("no response received from service",reply);
assertEquals(response2,reply);
try {
greeter.testRpcLitFault("BadRecordLitFault");
fail("Should have thrown BadRecoedLitFault");
}
catch ( BadRecordLitFault ex) {
assertNotNull(ex.getFaultInfo());
}
try {
greeter.testRpcLitFault("NoSuchCodeLitFault");
fail("Should have thrown NoSuchCodeLitFault exception");
}
catch ( NoSuchCodeLitFault nslf) {
assertNotNull(nslf.getFaultInfo());
assertNotNull(nslf.getFaultInfo().getCode());
}
}
((java.io.Closeable)greeter).close();
}
IterativeVerifier UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testDocBasicConnection() throws Exception {
QName serviceName=new QName("http://apache.org/hello_world_doc_lit","SOAPService2");
QName portName=new QName("http://apache.org/hello_world_doc_lit","SoapPort2");
URL wsdl=getWSDLURL("/wsdl/hello_world_doc_lit.wsdl");
SOAPService2 service=new SOAPService2(wsdl,serviceName);
String response1=new String("Hello Milestone-");
String response2=new String("Bonjour");
Greeter greeter=service.getPort(portName,Greeter.class);
Client client=ClientProxy.getClient(greeter);
client.getEndpoint().getOutInterceptors().add(new TibcoSoapActionInterceptor());
client.getOutInterceptors().add(new LoggingOutInterceptor());
client.getInInterceptors().add(new LoggingInInterceptor());
for (int idx=0; idx < 5; idx++) {
greeter.greetMeOneWay("test String");
String greeting=greeter.greetMe("Milestone-" + idx);
assertNotNull("no response received from service",greeting);
String exResponse=response1 + idx;
assertEquals(exResponse,greeting);
String reply=greeter.sayHi();
assertNotNull("no response received from service",reply);
assertEquals(response2,reply);
try {
greeter.pingMe();
fail("Should have thrown FaultException");
}
catch ( PingMeFault ex) {
assertNotNull(ex.getFaultInfo());
}
}
((java.io.Closeable)greeter).close();
}
IterativeVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testByteMessage() throws Exception {
QName serviceName=new QName("http://cxf.apache.org/hello_world_jms","HWByteMsgService");
URL wsdl=getWSDLURL("/wsdl/jms_test.wsdl");
HWByteMsgService service=new HWByteMsgService(wsdl,serviceName);
String response1=new String("Hello Milestone-");
String response2=new String("Bonjour");
HelloWorldPortType greeter=service.getHWSByteMsgPort();
for (int idx=0; idx < 2; idx++) {
String greeting=greeter.greetMe("Milestone-" + idx);
assertNotNull("no response received from service",greeting);
String exResponse=response1 + idx;
assertEquals(exResponse,greeting);
String reply=greeter.sayHi();
assertNotNull("no response received from service",reply);
assertEquals(response2,reply);
}
((java.io.Closeable)greeter).close();
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier IdentityVerifier EqualityVerifier IgnoredMethod HybridVerifier
@Ignore @Test public void testAsyncCall() throws Exception {
QName serviceName=new QName("http://cxf.apache.org/hello_world_jms","HelloWorldService");
QName portName=new QName("http://cxf.apache.org/hello_world_jms","HelloWorldPort");
URL wsdl=getWSDLURL("/wsdl/jms_test.wsdl");
HelloWorldService service=new HelloWorldService(wsdl,serviceName);
HelloWorldPortType greeter=service.getPort(portName,HelloWorldPortType.class);
final Thread thread=Thread.currentThread();
class TestAsyncHandler implements AsyncHandler {
String expected;
TestAsyncHandler( String x){
expected=x;
}
public String getExpected(){
return expected;
}
public void handleResponse( Response response){
try {
Thread thread2=Thread.currentThread();
assertNotSame(thread,thread2);
assertEquals("Hello " + expected,response.get());
}
catch ( InterruptedException e) {
e.printStackTrace();
}
catch ( ExecutionException e) {
e.printStackTrace();
}
}
}
TestAsyncHandler h1=new TestAsyncHandler("Homer");
TestAsyncHandler h2=new TestAsyncHandler("Maggie");
TestAsyncHandler h3=new TestAsyncHandler("Bart");
TestAsyncHandler h4=new TestAsyncHandler("Lisa");
TestAsyncHandler h5=new TestAsyncHandler("Marge");
Future> f1=greeter.greetMeAsync("Santa's Little Helper",new TestAsyncHandler("Santa's Little Helper"));
f1.get();
f1=greeter.greetMeAsync("PauseForTwoSecs Santa's Little Helper",new TestAsyncHandler("Santa's Little Helper"));
long start=System.currentTimeMillis();
f1=greeter.greetMeAsync("PauseForTwoSecs " + h1.getExpected(),h1);
Future> f2=greeter.greetMeAsync("PauseForTwoSecs " + h2.getExpected(),h2);
Future> f3=greeter.greetMeAsync("PauseForTwoSecs " + h3.getExpected(),h3);
Future> f4=greeter.greetMeAsync("PauseForTwoSecs " + h4.getExpected(),h4);
Future> f5=greeter.greetMeAsync("PauseForTwoSecs " + h5.getExpected(),h5);
long mid=System.currentTimeMillis();
assertEquals("Hello " + h1.getExpected(),f1.get());
assertEquals("Hello " + h2.getExpected(),f2.get());
assertEquals("Hello " + h3.getExpected(),f3.get());
assertEquals("Hello " + h4.getExpected(),f4.get());
assertEquals("Hello " + h5.getExpected(),f5.get());
long end=System.currentTimeMillis();
assertTrue("Time too long: " + (mid - start),(mid - start) < 1000);
assertTrue((end - mid) > 1000);
f1=null;
f2=null;
f3=null;
f4=null;
f5=null;
((java.io.Closeable)greeter).close();
greeter=null;
service=null;
System.gc();
}
APIUtilityVerifier BranchVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testContextPropagation() throws Exception {
final String testReturnPropertyName="Test_Prop";
final String testIgnoredPropertyName="Test_Prop_No_Return";
QName serviceName=new QName("http://cxf.apache.org/hello_world_jms","HelloWorldService");
QName portName=new QName("http://cxf.apache.org/hello_world_jms","HelloWorldPort");
URL wsdl=getWSDLURL("/wsdl/jms_test.wsdl");
HelloWorldService service=new HelloWorldService(wsdl,serviceName);
HelloWorldPortType greeter=service.getPort(portName,HelloWorldPortType.class);
Map requestContext=((BindingProvider)greeter).getRequestContext();
JMSMessageHeadersType requestHeader=new JMSMessageHeadersType();
requestHeader.setJMSCorrelationID("JMS_SAMPLE_CORRELATION_ID");
requestHeader.setJMSExpiration(3600000L);
JMSPropertyType propType=new JMSPropertyType();
propType.setName(testReturnPropertyName);
propType.setValue("mustReturn");
requestHeader.getProperty().add(propType);
propType=new JMSPropertyType();
propType.setName(testIgnoredPropertyName);
propType.setValue("mustNotReturn");
requestContext.put(JMSConstants.JMS_CLIENT_REQUEST_HEADERS,requestHeader);
String greeting=greeter.greetMe("Milestone-");
assertNotNull("no response received from service",greeting);
assertEquals("Hello Milestone-",greeting);
Map responseContext=((BindingProvider)greeter).getResponseContext();
JMSMessageHeadersType responseHdr=(JMSMessageHeadersType)responseContext.get(JMSConstants.JMS_CLIENT_RESPONSE_HEADERS);
if (responseHdr == null) {
fail("response Header should not be null");
}
assertTrue("CORRELATION ID should match :","JMS_SAMPLE_CORRELATION_ID".equals(responseHdr.getJMSCorrelationID()));
assertTrue("response Headers must conain the app property set in request context.",responseHdr.getProperty() != null);
boolean found=false;
for ( JMSPropertyType p : responseHdr.getProperty()) {
if (testReturnPropertyName.equals(p.getName())) {
found=true;
}
}
assertTrue("response Headers must match the app property set in request context.",found);
((Closeable)greeter).close();
}
IterativeVerifier UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testConnectionsWithinSpring() throws Exception {
BusFactory.setDefaultBus(null);
BusFactory.setThreadDefaultBus(null);
ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext(new String[]{"/org/apache/cxf/systest/jms/JMSClients.xml"});
try {
String wsdlString2="classpath:wsdl/jms_test.wsdl";
wsdlStrings.add(wsdlString2);
broker.updateWsdl((Bus)ctx.getBean("cxf"),wsdlString2);
HelloWorldPortType greeter=(HelloWorldPortType)ctx.getBean("jmsRPCClient");
try {
for (int idx=0; idx < 5; idx++) {
String greeting=greeter.greetMe("Milestone-" + idx);
assertNotNull("no response received from service",greeting);
String exResponse="Hello Milestone-" + idx;
assertEquals(exResponse,greeting);
String reply=greeter.sayHi();
assertEquals("Bonjour",reply);
try {
greeter.testRpcLitFault("BadRecordLitFault");
fail("Should have thrown BadRecoedLitFault");
}
catch ( BadRecordLitFault ex) {
assertNotNull(ex.getFaultInfo());
}
try {
greeter.testRpcLitFault("NoSuchCodeLitFault");
fail("Should have thrown NoSuchCodeLitFault exception");
}
catch ( NoSuchCodeLitFault nslf) {
assertNotNull(nslf.getFaultInfo());
assertNotNull(nslf.getFaultInfo().getCode());
}
}
}
catch ( UndeclaredThrowableException ex) {
ctx.close();
throw (Exception)ex.getCause();
}
HelloWorldOneWayPort greeter1=(HelloWorldOneWayPort)ctx.getBean("jmsQueueOneWayServiceClient");
assertNotNull(greeter1);
try {
greeter1.greetMeOneWay("hello");
}
catch ( Exception ex) {
fail("There should not throw the exception" + ex);
}
}
finally {
ctx.close();
BusFactory.setDefaultBus(getBus());
BusFactory.setThreadDefaultBus(getBus());
}
}
Class: org.apache.cxf.systest.jms.JMSTestMtom APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testOutMTOM() throws Exception {
QName serviceName=new QName("http://cxf.apache.org/jms_mtom","JMSMTOMService");
QName portName=new QName("http://cxf.apache.org/jms_mtom","MTOMPort");
URL wsdl=getWSDLURL("/wsdl/jms_test_mtom.wsdl");
JMSOutMTOMService service=new JMSOutMTOMService(wsdl,serviceName);
JMSMTOMPortType mtom=service.getPort(portName,JMSMTOMPortType.class);
URL fileURL=this.getClass().getResource("/org/apache/cxf/systest/jms/JMSClientServerTest.class");
DataHandler handler1=new DataHandler(fileURL);
int size=handler1.getInputStream().available();
DataHandler ret=mtom.testOutMtom();
byte bytes[]=IOUtils.readBytesFromStream(ret.getInputStream());
Assert.assertEquals("The response file is not same with the original file.",size,bytes.length);
((Closeable)mtom).close();
}
Class: org.apache.cxf.systest.jms.JaxWsAPITest InternalCallVerifier EqualityVerifier
@Test public void testGreeterUsingJaxWSAPI() throws Exception {
QName serviceName=new QName("http://apache.org/hello_world_doc_lit","SOAPService2");
QName portName=new QName("http://apache.org/hello_world_doc_lit","SoapPort2");
URL wsdl=getWSDLURL("/wsdl/hello_world_doc_lit.wsdl");
SOAPService2 service=new SOAPService2(wsdl,serviceName);
Greeter greeter=markForClose(service.getPort(portName,Greeter.class,cff));
Client client=ClientProxy.getClient(greeter);
client.getEndpoint().getOutInterceptors().add(new TibcoSoapActionInterceptor());
greeter.greetMeOneWay("test String");
String greeting=greeter.greetMe("Chris");
Assert.assertEquals("Hello Chris",greeting);
}
Class: org.apache.cxf.systest.jms.continuations.JMSContinuationsClientServerTest InternalCallVerifier EqualityVerifier
@Test public void testContinuationWithTimeout() throws Exception {
QName serviceName=new QName("http://cxf.apache.org/hello_world_jms","HelloWorldService");
QName portName=new QName("http://cxf.apache.org/hello_world_jms","HelloWorldPort");
URL wsdl=getWSDLURL("/org/apache/cxf/systest/jms/continuations/jms_test.wsdl");
HelloWorldService service=new HelloWorldService(wsdl,serviceName);
HelloWorldPortType greeter=markForClose(service.getPort(portName,HelloWorldPortType.class,cff));
Assert.assertEquals("Hi Fred Ruby",greeter.greetMe("Fred"));
}
Class: org.apache.cxf.systest.jms.multitransport.MultiTransportClientServerTest IterativeVerifier UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testMultiTransportInOneService() throws Exception {
QName portName1=new QName("http://apache.org/hello_world_doc_lit","HttpPort");
QName portName2=new QName("http://apache.org/hello_world_doc_lit","JMSPort");
URL wsdl=getClass().getResource("/wsdl/hello_world_doc_lit.wsdl");
Assert.assertNotNull(wsdl);
MultiTransportService service=new MultiTransportService(wsdl,serviceName);
String response1=new String("Hello Milestone-");
String response2=new String("Bonjour");
Greeter greeter=service.getPort(portName1,Greeter.class);
TestUtil.updateAddressPort(greeter,PORT);
for (int idx=0; idx < 5; idx++) {
String greeting=greeter.greetMe("Milestone-" + idx);
Assert.assertNotNull("no response received from service",greeting);
String exResponse=response1 + idx;
Assert.assertEquals(exResponse,greeting);
String reply=greeter.sayHi();
Assert.assertNotNull("no response received from service",reply);
Assert.assertEquals(response2,reply);
try {
greeter.pingMe();
Assert.fail("Should have thrown FaultException");
}
catch ( PingMeFault ex) {
Assert.assertNotNull(ex.getFaultInfo());
}
}
((java.io.Closeable)greeter).close();
greeter=null;
greeter=service.getPort(portName2,Greeter.class,cff);
for (int idx=0; idx < 5; idx++) {
String greeting=greeter.greetMe("Milestone-" + idx);
Assert.assertNotNull("no response received from service",greeting);
String exResponse=response1 + idx;
Assert.assertEquals(exResponse,greeting);
String reply=greeter.sayHi();
Assert.assertNotNull("no response received from service",reply);
Assert.assertEquals(response2,reply);
try {
greeter.pingMe();
Assert.fail("Should have thrown FaultException");
}
catch ( PingMeFault ex) {
Assert.assertNotNull(ex.getFaultInfo());
}
}
((java.io.Closeable)greeter).close();
}
Class: org.apache.cxf.systest.jms.security.JMSWSSecurityTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testUnsignedSAML2AudienceRestrictionTokenURI() throws Exception {
QName serviceName=new QName("http://cxf.apache.org/hello_world_jms","HelloWorldService");
QName portName=new QName("http://cxf.apache.org/hello_world_jms","HelloWorldPort");
URL wsdl=getWSDLURL("/wsdl/jms_test.wsdl");
HelloWorldService service=new HelloWorldService(wsdl,serviceName);
String response=new String("Bonjour");
HelloWorldPortType greeter=service.getPort(portName,HelloWorldPortType.class);
SamlCallbackHandler callbackHandler=new SamlCallbackHandler();
callbackHandler.setSignAssertion(true);
callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
ConditionsBean conditions=new ConditionsBean();
conditions.setTokenPeriodMinutes(5);
List audiences=new ArrayList<>();
audiences.add("jms:jndi:dynamicQueues/test.jmstransport.text");
AudienceRestrictionBean audienceRestrictionBean=new AudienceRestrictionBean();
audienceRestrictionBean.setAudienceURIs(audiences);
conditions.setAudienceRestrictions(Collections.singletonList(audienceRestrictionBean));
callbackHandler.setConditions(conditions);
Map outProperties=new HashMap();
outProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.SAML_TOKEN_UNSIGNED);
outProperties.put(WSHandlerConstants.SAML_CALLBACK_REF,callbackHandler);
WSS4JOutInterceptor outInterceptor=new WSS4JOutInterceptor(outProperties);
Client client=ClientProxy.getClient(greeter);
client.getOutInterceptors().add(outInterceptor);
String reply=greeter.sayHi();
assertNotNull("no response received from service",reply);
assertEquals(response,reply);
((java.io.Closeable)greeter).close();
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testUnsignedSAML2Token() throws Exception {
QName serviceName=new QName("http://cxf.apache.org/hello_world_jms","HelloWorldService");
QName portName=new QName("http://cxf.apache.org/hello_world_jms","HelloWorldPort");
URL wsdl=getWSDLURL("/wsdl/jms_test.wsdl");
HelloWorldService service=new HelloWorldService(wsdl,serviceName);
String response=new String("Bonjour");
HelloWorldPortType greeter=service.getPort(portName,HelloWorldPortType.class);
SamlCallbackHandler callbackHandler=new SamlCallbackHandler();
callbackHandler.setSignAssertion(true);
callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
Map outProperties=new HashMap();
outProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.SAML_TOKEN_UNSIGNED);
outProperties.put(WSHandlerConstants.SAML_CALLBACK_REF,callbackHandler);
WSS4JOutInterceptor outInterceptor=new WSS4JOutInterceptor(outProperties);
Client client=ClientProxy.getClient(greeter);
client.getOutInterceptors().add(outInterceptor);
String reply=greeter.sayHi();
assertNotNull("no response received from service",reply);
assertEquals(response,reply);
((java.io.Closeable)greeter).close();
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testUnsignedSAML2AudienceRestrictionTokenServiceName() throws Exception {
QName serviceName=new QName("http://cxf.apache.org/hello_world_jms","HelloWorldService");
QName portName=new QName("http://cxf.apache.org/hello_world_jms","HelloWorldPort");
URL wsdl=getWSDLURL("/wsdl/jms_test.wsdl");
HelloWorldService service=new HelloWorldService(wsdl,serviceName);
String response=new String("Bonjour");
HelloWorldPortType greeter=service.getPort(portName,HelloWorldPortType.class);
SamlCallbackHandler callbackHandler=new SamlCallbackHandler();
callbackHandler.setSignAssertion(true);
callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
ConditionsBean conditions=new ConditionsBean();
conditions.setTokenPeriodMinutes(5);
List audiences=new ArrayList<>();
audiences.add("{http://cxf.apache.org/hello_world_jms}HelloWorldService");
AudienceRestrictionBean audienceRestrictionBean=new AudienceRestrictionBean();
audienceRestrictionBean.setAudienceURIs(audiences);
conditions.setAudienceRestrictions(Collections.singletonList(audienceRestrictionBean));
callbackHandler.setConditions(conditions);
Map outProperties=new HashMap();
outProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.SAML_TOKEN_UNSIGNED);
outProperties.put(WSHandlerConstants.SAML_CALLBACK_REF,callbackHandler);
WSS4JOutInterceptor outInterceptor=new WSS4JOutInterceptor(outProperties);
Client client=ClientProxy.getClient(greeter);
client.getOutInterceptors().add(outInterceptor);
String reply=greeter.sayHi();
assertNotNull("no response received from service",reply);
assertEquals(response,reply);
((java.io.Closeable)greeter).close();
}
Class: org.apache.cxf.systest.js.JSClientServerTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testJSPayloadMode() throws Exception {
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
QName serviceName=new QName(NS,"SOAPService_Test1");
QName portName=new QName(NS,"SoapPort_Test1");
SOAPServiceTest1 service=new SOAPServiceTest1(wsdl,serviceName);
assertNotNull(service);
String response1=new String("TestGreetMeResponse");
String response2=new String("TestSayHiResponse");
try {
Greeter greeter=service.getPort(portName,Greeter.class);
updateAddressPort(greeter,JSX_PORT);
String greeting=greeter.greetMe("TestGreetMeRequest");
assertNotNull("no response received from service",greeting);
assertEquals(response1,greeting);
String reply=greeter.sayHi();
assertNotNull("no response received from service",reply);
assertEquals(response2,reply);
}
catch ( UndeclaredThrowableException ex) {
ex.printStackTrace();
throw (Exception)ex.getCause();
}
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testJSMessageMode() throws Exception {
QName serviceName=new QName(NS,"SOAPService");
QName portName=new QName(NS,"SoapPort");
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
assertNotNull(service);
String response1=new String("TestGreetMeResponse");
String response2=new String("TestSayHiResponse");
try {
Greeter greeter=service.getPort(portName,Greeter.class);
updateAddressPort(greeter,JS_PORT);
String greeting=greeter.greetMe("TestGreetMeRequest");
assertNotNull("no response received from service",greeting);
assertEquals(response1,greeting);
String reply=greeter.sayHi();
assertNotNull("no response received from service",reply);
assertEquals(response2,reply);
}
catch ( UndeclaredThrowableException ex) {
ex.printStackTrace();
throw (Exception)ex.getCause();
}
}
Class: org.apache.cxf.systest.kerberos.jaxrs.kerberos.JAXRSKerberosBookTest InternalCallVerifier EqualityVerifier
@Test public void testGetBookWithInterceptor() throws Exception {
if (!runTests) {
return;
}
WebClient wc=WebClient.create("http://localhost:" + PORT + "/bookstore/books/123");
KerberosAuthOutInterceptor kbInterceptor=new KerberosAuthOutInterceptor();
AuthorizationPolicy policy=new AuthorizationPolicy();
policy.setAuthorizationType(HttpAuthHeader.AUTH_TYPE_NEGOTIATE);
policy.setAuthorization("alice");
policy.setUserName("alice");
policy.setPassword("alice");
kbInterceptor.setPolicy(policy);
kbInterceptor.setCredDelegation(true);
WebClient.getConfig(wc).getOutInterceptors().add(new LoggingOutInterceptor());
WebClient.getConfig(wc).getOutInterceptors().add(kbInterceptor);
kbInterceptor.setServicePrincipalName("bob@service.ws.apache.org");
kbInterceptor.setServiceNameType(GSSName.NT_HOSTBASED_SERVICE);
Book b=wc.get(Book.class);
Assert.assertEquals(b.getId(),123);
}
Class: org.apache.cxf.systest.lifecycle.LifeCycleTest BranchVerifier BooleanVerifier InternalCallVerifier IdentityVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetActiveFeatures(){
assertNotNull("unexpected non-null ServerLifeCycleManager",manager);
manager.registerListener(new ServerLifeCycleListener(){
public void startServer( Server server){
org.apache.cxf.endpoint.Endpoint endpoint=server.getEndpoint();
updateMap(startNotificationMap,endpoint.getEndpointInfo().getAddress());
String portName=endpoint.getEndpointInfo().getName().getLocalPart();
if ("SoapPort".equals(portName)) {
List active=endpoint.getActiveFeatures();
assertNotNull(active);
assertEquals(1,active.size());
assertTrue(active.get(0) instanceof WSAddressingFeature);
assertSame(active.get(0),AbstractFeature.getActive(active,WSAddressingFeature.class));
}
else {
List active=endpoint.getActiveFeatures();
assertNotNull(active);
assertEquals(0,active.size());
assertNull(AbstractFeature.getActive(active,WSAddressingFeature.class));
}
}
public void stopServer( Server server){
updateMap(stopNotificationMap,server.getEndpoint().getEndpointInfo().getAddress());
}
}
);
Endpoint greeter=Endpoint.publish(ADDRESSES[0],new GreeterImpl());
Endpoint control=Endpoint.publish(ADDRESSES[1],new ControlImpl());
greeter.stop();
control.stop();
for (int i=0; i < 2; i++) {
verifyNotification(startNotificationMap,ADDRESSES[i],1);
verifyNotification(stopNotificationMap,ADDRESSES[i],1);
}
}
Class: org.apache.cxf.systest.management.CountersClientServerTest APIUtilityVerifier IterativeVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCountersWithInstrumentationManager() throws Exception {
Bus bus=getStaticBus();
BusFactory.setDefaultBus(bus);
bus.getExtension(WorkQueueManager.class);
CounterRepository cr=bus.getExtension(CounterRepository.class);
InstrumentationManager im=bus.getExtension(InstrumentationManager.class);
assertNotNull(im);
InstrumentationManagerImpl impl=(InstrumentationManagerImpl)im;
assertTrue(impl.isEnabled());
assertNotNull(impl.getMBeanServer());
MBeanServer mbs=im.getMBeanServer();
ObjectName name=new ObjectName(ManagementConstants.DEFAULT_DOMAIN_NAME + ":" + ManagementConstants.BUS_ID_PROP+ "=cxf"+ bus.hashCode()+ ",*");
SOAPService service=new SOAPService();
assertNotNull(service);
Greeter greeter=service.getPort(portName,Greeter.class);
updateAddressPort(greeter,PORT);
String response=new String("Bonjour");
String reply=greeter.sayHi();
assertEquals("The Counters are not create yet",4,cr.getCounters().size());
Set> counterNames=mbs.queryNames(name,null);
assertEquals("The Counters are not export to JMX: " + counterNames,4 + 3,counterNames.size());
ObjectName sayHiCounter=new ObjectName(ManagementConstants.DEFAULT_DOMAIN_NAME + ":operation=\"sayHi\",*");
Set> s=mbs.queryNames(sayHiCounter,null);
Iterator> it=s.iterator();
while (it.hasNext()) {
ObjectName counterName=(ObjectName)it.next();
Object val=mbs.getAttribute(counterName,"NumInvocations");
assertEquals("Wrong Counters Number of Invocations",val,1);
}
reply=greeter.sayHi();
assertNotNull("no response received from service",reply);
assertEquals(response,reply);
s=mbs.queryNames(sayHiCounter,null);
it=s.iterator();
while (it.hasNext()) {
ObjectName counterName=(ObjectName)it.next();
Object val=mbs.getAttribute(counterName,"NumInvocations");
assertEquals("Wrong Counters Number of Invocations",val,2);
}
greeter.greetMeOneWay("hello");
for (int count=0; count < 10; count++) {
if (6 != cr.getCounters().size()) {
Thread.sleep(100);
}
else {
break;
}
}
assertEquals("The Counters are not create yet",6,cr.getCounters().size());
for (int count=0; count < 10; count++) {
if (10 > mbs.queryNames(name,null).size()) {
Thread.sleep(100);
}
else {
break;
}
}
counterNames=mbs.queryNames(name,null);
assertEquals("The Counters are not export to JMX " + counterNames,6 + 4,counterNames.size());
ObjectName greetMeOneWayCounter=new ObjectName(ManagementConstants.DEFAULT_DOMAIN_NAME + ":operation=\"greetMeOneWay\",*");
s=mbs.queryNames(greetMeOneWayCounter,null);
it=s.iterator();
while (it.hasNext()) {
ObjectName counterName=(ObjectName)it.next();
Object val=mbs.getAttribute(counterName,"NumInvocations");
assertEquals("Wrong Counters Number of Invocations",val,1);
}
}
Class: org.apache.cxf.systest.management.ManagedBusTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testTwoSameNamedEndpoint() throws Exception {
SpringBusFactory factory=new SpringBusFactory();
Bus bus=factory.createBus();
try {
InstrumentationManager im=bus.getExtension(InstrumentationManager.class);
assertNotNull(im);
InstrumentationManagerImpl imi=(InstrumentationManagerImpl)im;
imi.setServer(ManagementFactory.getPlatformMBeanServer());
imi.setEnabled(true);
imi.init();
Greeter greeter1=new GreeterImpl();
JaxWsServerFactoryBean svrFactory=new JaxWsServerFactoryBean();
svrFactory.setAddress("http://localhost:" + SERVICE_PORT + "/Hello");
svrFactory.setServiceBean(greeter1);
svrFactory.getProperties(true).put("managed.endpoint.name","greeter1");
svrFactory.create();
Greeter greeter2=new GreeterImpl();
svrFactory=new JaxWsServerFactoryBean();
svrFactory.setAddress("http://localhost:" + SERVICE_PORT + "/Hello2");
svrFactory.setServiceBean(greeter2);
svrFactory.getProperties(true).put("managed.endpoint.name","greeter2");
svrFactory.create();
MBeanServer mbs=im.getMBeanServer();
ObjectName name=new ObjectName(ManagementConstants.DEFAULT_DOMAIN_NAME + ":type=Bus.Service.Endpoint,*");
Set> s=mbs.queryMBeans(name,null);
assertEquals(2,s.size());
}
finally {
bus.shutdown(true);
}
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testManagedSpringBus() throws Exception {
SpringBusFactory factory=new SpringBusFactory();
Bus bus=factory.createBus();
InstrumentationManager im=bus.getExtension(InstrumentationManager.class);
assertNotNull(im);
InstrumentationManagerImpl imi=(InstrumentationManagerImpl)im;
assertEquals("service:jmx:rmi:///jndi/rmi://localhost:9913/jmxrmi",imi.getJMXServiceURL());
assertTrue(!imi.isEnabled());
assertNull(imi.getMBeanServer());
im.register(imi,new ObjectName("org.apache.cxf:foo=bar"));
bus.shutdown(true);
}
Class: org.apache.cxf.systest.management.ManagedClientServerTest APIUtilityVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testManagedEndpoint() throws Exception {
Bus bus=getStaticBus();
BusFactory.setDefaultBus(bus);
InstrumentationManager im=bus.getExtension(InstrumentationManager.class);
assertNotNull(im);
InstrumentationManagerImpl impl=(InstrumentationManagerImpl)im;
assertTrue(impl.isEnabled());
assertNotNull(impl.getMBeanServer());
MBeanServer mbs=im.getMBeanServer();
ObjectName name=new ObjectName(ManagementConstants.DEFAULT_DOMAIN_NAME + ":type=Bus.Service.Endpoint,*");
Set> s=mbs.queryNames(name,null);
assertEquals(1,s.size());
name=(ObjectName)s.iterator().next();
Object val=mbs.invoke(name,"getState",new Object[0],new String[0]);
assertEquals("Service should have been started.","STARTED",val);
SOAPService service=new SOAPService();
assertNotNull(service);
Greeter greeter=service.getPort(portName,Greeter.class);
updateAddressPort(greeter,PORT);
String response=new String("Bonjour");
String reply=greeter.sayHi();
assertNotNull("no response received from service",reply);
assertEquals(response,reply);
mbs.invoke(name,"stop",new Object[0],new String[0]);
val=mbs.getAttribute(name,"State");
assertEquals("Service should have been stopped.","STOPPED",val);
try {
reply=greeter.sayHi();
fail("Endpoint should not be active at this point.");
}
catch ( Exception ex) {
}
mbs.invoke(name,"start",new Object[0],new String[0]);
val=mbs.invoke(name,"getState",new Object[0],new String[0]);
assertEquals("Service should have been started.","STARTED",val);
reply=greeter.sayHi();
assertNotNull("no response received from service",reply);
assertEquals(response,reply);
mbs.invoke(name,"destroy",new Object[0],new String[0]);
try {
mbs.getMBeanInfo(name);
fail("destroy failed to unregister MBean.");
}
catch ( InstanceNotFoundException e) {
}
}
Class: org.apache.cxf.systest.mtom.ClientMtomXopTest APIUtilityVerifier InternalCallVerifier NullVerifier
@org.junit.Ignore @Test public void testMtoMString() throws Exception {
TestMtom mtomPort=createPort(MTOM_SERVICE,MTOM_PORT,TestMtom.class,true,false);
InputStream pre=this.getClass().getResourceAsStream("/wsdl/mtom_xop.wsdl");
long fileSize=0;
for (int i=pre.read(); i != -1; i=pre.read()) {
fileSize++;
}
byte[] data=new byte[(int)fileSize];
this.getClass().getResourceAsStream("/wsdl/mtom_xop.wsdl").read(data);
String stringValue=new String(data,"utf-8");
XopStringType xsv=new XopStringType();
xsv.setAttachinfo(stringValue);
xsv.setName("eman");
XopStringType r=mtomPort.testXopString(xsv);
assertNotNull(r);
}
Class: org.apache.cxf.systest.mtom.MtomPolicyTest BooleanVerifier InternalCallVerifier
@Test public void testRequiredMtom() throws Exception {
String address="http://localhost:" + PORT + "/EchoService";
setupServer(true,address);
sendMtomMessage(address);
Node res=testUtilities.invoke(address,"http://schemas.xmlsoap.org/soap/http","nonmtom.xml");
NodeList list=testUtilities.assertValid("//faultstring",res);
String text=list.item(0).getTextContent();
assertTrue(text.contains("These policy alternatives can not be satisfied: "));
assertTrue(text.contains("{http://schemas.xmlsoap.org/ws/2004/09/policy/optimizedmimeserialization}" + "OptimizedMimeSerialization"));
}
Class: org.apache.cxf.systest.mtom.MtomServerTest BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testURLBasedAttachment() throws Exception {
JaxWsServerFactoryBean sf=new JaxWsServerFactoryBean();
sf.setServiceBean(new EchoService());
sf.setBus(getStaticBus());
String address="http://localhost:" + PORT2 + "/EchoService";
sf.setAddress(address);
Map props=new HashMap();
props.put(Message.MTOM_ENABLED,"true");
sf.setProperties(props);
Server server=sf.create();
server.getEndpoint().getService().getDataBinding().setMtomThreshold(0);
servStatic(getClass().getResource("mtom-policy.xml"),"http://localhost:" + PORT2 + "/policy.xsd");
EndpointInfo ei=new EndpointInfo(null,HTTP_ID);
ei.setAddress(address);
ConduitInitiatorManager conduitMgr=getStaticBus().getExtension(ConduitInitiatorManager.class);
ConduitInitiator conduitInit=conduitMgr.getConduitInitiator("http://schemas.xmlsoap.org/soap/http");
Conduit conduit=conduitInit.getConduit(ei,getStaticBus());
TestUtilities.TestMessageObserver obs=new TestUtilities.TestMessageObserver();
conduit.setMessageObserver(obs);
Message m=new MessageImpl();
String ct="multipart/related; type=\"application/xop+xml\"; " + "start=\"\"; " + "start-info=\"text/xml; charset=utf-8\"; "+ "boundary=\"----=_Part_4_701508.1145579811786\"";
m.put(Message.CONTENT_TYPE,ct);
conduit.prepare(m);
OutputStream os=m.getContent(OutputStream.class);
InputStream is=testUtilities.getResourceAsStream("request-url-attachment");
if (is == null) {
throw new RuntimeException("Could not find resource " + "request");
}
ByteArrayOutputStream bout=new ByteArrayOutputStream();
IOUtils.copy(is,bout);
String s=bout.toString(StandardCharsets.UTF_8.name());
s=s.replaceAll(":9036/",":" + PORT2 + "/");
os.write(s.getBytes(StandardCharsets.UTF_8));
os.flush();
is.close();
os.close();
byte[] res=obs.getResponseStream().toByteArray();
MessageImpl resMsg=new MessageImpl();
resMsg.setContent(InputStream.class,new ByteArrayInputStream(res));
resMsg.put(Message.CONTENT_TYPE,obs.getResponseContentType());
resMsg.setExchange(new ExchangeImpl());
AttachmentDeserializer deserializer=new AttachmentDeserializer(resMsg);
deserializer.initializeAttachments();
Collection attachments=resMsg.getAttachments();
assertNotNull(attachments);
assertEquals(1,attachments.size());
Attachment inAtt=attachments.iterator().next();
ByteArrayOutputStream out=new ByteArrayOutputStream();
IOUtils.copy(inAtt.getDataHandler().getInputStream(),out);
out.close();
assertTrue("Wrong size: " + out.size() + "\n"+ out.toString(),out.size() > 970 && out.size() < 1020);
unregisterServStatic("http://localhost:" + PORT2 + "/policy.xsd");
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testMtomRequest() throws Exception {
JaxWsServerFactoryBean sf=new JaxWsServerFactoryBean();
sf.setServiceBean(new EchoService());
sf.setBus(getStaticBus());
String address="http://localhost:" + PORT1 + "/EchoService";
sf.setAddress(address);
Map props=new HashMap();
props.put(Message.MTOM_ENABLED,"true");
sf.setProperties(props);
sf.create();
EndpointInfo ei=new EndpointInfo(null,HTTP_ID);
ei.setAddress(address);
ConduitInitiatorManager conduitMgr=getStaticBus().getExtension(ConduitInitiatorManager.class);
ConduitInitiator conduitInit=conduitMgr.getConduitInitiator("http://schemas.xmlsoap.org/soap/http");
Conduit conduit=conduitInit.getConduit(ei,getStaticBus());
TestUtilities.TestMessageObserver obs=new TestUtilities.TestMessageObserver();
conduit.setMessageObserver(obs);
Message m=new MessageImpl();
String ct="multipart/related; type=\"application/xop+xml\"; " + "start=\"\"; " + "start-info=\"text/xml\"; "+ "boundary=\"----=_Part_4_701508.1145579811786\"";
m.put(Message.CONTENT_TYPE,ct);
conduit.prepare(m);
OutputStream os=m.getContent(OutputStream.class);
InputStream is=testUtilities.getResourceAsStream("request");
if (is == null) {
throw new RuntimeException("Could not find resource " + "request");
}
IOUtils.copy(is,os);
os.flush();
is.close();
os.close();
byte[] res=obs.getResponseStream().toByteArray();
MessageImpl resMsg=new MessageImpl();
resMsg.setContent(InputStream.class,new ByteArrayInputStream(res));
resMsg.put(Message.CONTENT_TYPE,obs.getResponseContentType());
resMsg.setExchange(new ExchangeImpl());
AttachmentDeserializer deserializer=new AttachmentDeserializer(resMsg);
deserializer.initializeAttachments();
Collection attachments=resMsg.getAttachments();
assertNotNull(attachments);
assertEquals(1,attachments.size());
Attachment inAtt=attachments.iterator().next();
ByteArrayOutputStream out=new ByteArrayOutputStream();
IOUtils.copy(inAtt.getDataHandler().getInputStream(),out);
out.close();
assertEquals(27364,out.size());
}
Class: org.apache.cxf.systest.mtom_schema_validation.MTOMProviderSchemaValidationTest InternalCallVerifier EqualityVerifier
@Test public void testSchemaValidation() throws Exception {
HelloWS port=createService();
Hello request=new Hello();
request.setArg0("value");
URL wsdl=getClass().getResource("/wsdl_systest/mtom_provider_validate.wsdl");
File attachment=new File(wsdl.getFile());
request.setFile(new DataHandler(new FileDataSource(attachment)));
HelloResponse response=port.hello(request);
assertEquals("Hello CXF",response.getReturn());
}
Class: org.apache.cxf.systest.nested_callback.CallbackClientServerTest InternalCallVerifier EqualityVerifier
@Test public void testCallback() throws Exception {
Object implementor=new CallbackImpl();
String address="http://localhost:" + CB_PORT + "/CallbackContext/NestedCallbackPort";
Endpoint.publish(address,implementor);
URL wsdlURL=getClass().getResource("/wsdl/nested_callback.wsdl");
SOAPService ss=new SOAPService(wsdlURL,SERVICE_NAME);
ServerPortType port=ss.getPort(PORT_NAME,ServerPortType.class);
updateAddressPort(port,PORT);
EndpointReferenceType ref=null;
try {
ref=EndpointReferenceUtils.getEndpointReference(wsdlURL,SERVICE_NAME_CALLBACK,PORT_NAME_CALLBACK.getLocalPart());
EndpointReferenceUtils.setInterfaceName(ref,PORT_TYPE_CALLBACK);
EndpointReferenceUtils.setAddress(ref,address);
}
catch ( Exception e) {
e.printStackTrace();
}
NestedCallback callbackObject=new NestedCallback();
Source source=EndpointReferenceUtils.convertToXML(ref);
W3CEndpointReference w3cEpr=new W3CEndpointReference(source);
callbackObject.setCallback(w3cEpr);
String resp=port.registerCallback(callbackObject);
assertEquals("registerCallback called",resp);
}
Class: org.apache.cxf.systest.outofband.header.OOBHeaderTest BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testBasicConnection() throws Exception {
URL wsdl=getClass().getResource("/wsdl/doc_lit_bare.wsdl");
assertNotNull("WSDL is null",wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
assertNotNull("Service is null",service);
PutLastTradedPricePortType putLastTradedPrice=service.getPort(portName,PutLastTradedPricePortType.class);
updateAddressPort(putLastTradedPrice,PORT);
TradePriceData priceData=new TradePriceData();
priceData.setTickerPrice(1.0f);
priceData.setTickerSymbol("CELTIX");
assertFalse(check(0,putLastTradedPrice,false,true,priceData));
assertFalse(check(1,putLastTradedPrice,false,true,priceData));
assertTrue(check(2,putLastTradedPrice,false,true,priceData));
assertTrue(check(3,putLastTradedPrice,false,true,priceData));
assertFalse(check(0,putLastTradedPrice,true,true,priceData));
assertFalse(check(1,putLastTradedPrice,true,true,priceData));
assertFalse(check(2,putLastTradedPrice,true,true,priceData));
assertFalse(check(3,putLastTradedPrice,true,true,priceData));
assertTrue(check(0,putLastTradedPrice,false,false,priceData));
assertTrue(check(1,putLastTradedPrice,false,false,priceData));
assertTrue(check(2,putLastTradedPrice,false,false,priceData));
assertTrue(check(4,putLastTradedPrice,false,false,priceData));
assertTrue(check(0,putLastTradedPrice,true,false,priceData));
assertTrue(check(1,putLastTradedPrice,true,false,priceData));
assertTrue(check(2,putLastTradedPrice,true,false,priceData));
assertTrue(check(4,putLastTradedPrice,true,false,priceData));
}
Class: org.apache.cxf.systest.provider.AttachmentProviderXMLClientServerTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testRequestWithAttachment() throws Exception {
HttpURLConnection connection=(HttpURLConnection)new URL(ADDRESS).openConnection();
connection.setRequestMethod("POST");
String ct="multipart/related; type=\"text/xml\"; " + "start=\"rootPart\"; " + "boundary=\"----=_Part_4_701508.1145579811786\"";
connection.addRequestProperty("Content-Type",ct);
connection.setDoOutput(true);
InputStream is=getClass().getResourceAsStream("attachmentData");
IOUtils.copy(is,connection.getOutputStream());
connection.getOutputStream().close();
is.close();
assertTrue("wrong content type: " + connection.getContentType(),connection.getContentType().contains("multipart/related"));
String input=IOUtils.toString(connection.getInputStream());
int idx=input.indexOf("--uuid");
int idx2=input.indexOf("--uuid",idx + 5);
String root=input.substring(idx,idx2);
idx=root.indexOf("\r\n\r\n");
root=root.substring(idx).trim();
Document result=StaxUtils.read(new StringReader(root));
List resList=DOMUtils.findAllElementsByTagName(result.getDocumentElement(),"att");
assertEquals("Two attachments must've been encoded",2,resList.size());
verifyAttachment(resList,"foo","foobar");
verifyAttachment(resList,"bar","barbaz");
input=input.substring(idx2);
assertTrue(input.contains(""));
assertTrue(input.contains("ABCDEFGHIJKLMNOP"));
}
Class: org.apache.cxf.systest.provider.CXF4130Test APIUtilityVerifier IterativeVerifier BranchVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testCxf4130() throws Exception {
InputStream body=getClass().getResourceAsStream("cxf4130data.txt");
HttpClient client=new HttpClient();
PostMethod post=new PostMethod(ADDRESS);
post.setRequestEntity(new InputStreamRequestEntity(body,"text/xml"));
client.executeMethod(post);
Document doc=StaxUtils.read(post.getResponseBodyAsStream());
Element root=doc.getDocumentElement();
Node child=root.getFirstChild();
boolean foundBody=false;
while (child != null) {
if ("Body".equals(child.getLocalName())) {
foundBody=true;
assertEquals(1,child.getChildNodes().getLength());
assertEquals("FooResponse",child.getFirstChild().getLocalName());
}
child=child.getNextSibling();
}
assertTrue("Did not find the soap:Body element",foundBody);
}
Class: org.apache.cxf.systest.provider.ProviderClientServerTest IterativeVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSOAPMessageModeDocLit() throws Exception {
QName serviceName=new QName("http://apache.org/hello_world_soap_http","SOAPProviderService");
QName portName=new QName("http://apache.org/hello_world_soap_http","SoapProviderPort");
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
SOAPService service=new SOAPService(wsdl,serviceName);
assertNotNull(service);
String response1=new String("TestSOAPOutputPMessage");
String response2=new String("Bonjour");
try {
Greeter greeter=service.getPort(portName,Greeter.class);
setAddress(greeter,ADDRESS);
try {
greeter.greetMe("Return sayHi");
fail("Should have thrown an exception");
}
catch ( Exception ex) {
assertTrue(ex.getMessage().contains("sayHiResponse"));
}
for (int idx=0; idx < 2; idx++) {
String greeting=greeter.greetMe("Milestone-" + idx);
assertNotNull("no response received from service",greeting);
assertEquals(response1,greeting);
String reply=greeter.sayHi();
assertNotNull("no response received from service",reply);
assertEquals(response2,reply);
}
try {
greeter.greetMe("throwFault");
fail("Expected a fault");
}
catch ( SOAPFaultException ex) {
assertTrue(ex.getMessage().contains("Test Fault String"));
}
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
Class: org.apache.cxf.systest.provider.ProviderRPCClientServerTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSOAPMessageModeRPC() throws Exception {
QName serviceName=new QName("http://apache.org/hello_world_rpclit","SOAPServiceProviderRPCLit");
QName portName=new QName("http://apache.org/hello_world_rpclit","SoapPortProviderRPCLit1");
URL wsdl=getClass().getResource("/wsdl/hello_world_rpc_lit.wsdl");
assertNotNull(wsdl);
SOAPServiceRPCLit service=new SOAPServiceRPCLit(wsdl,serviceName);
assertNotNull(service);
String response1=new String("TestGreetMeResponseServerLogicalHandlerServerSOAPHandler");
String response2=new String("TestSayHiResponse");
GreeterRPCLit greeter=service.getPort(portName,GreeterRPCLit.class);
updateAddressPort(greeter,PORT);
String greeting=greeter.greetMe("Milestone-0");
assertNotNull("no response received from service",greeting);
assertEquals(response1,greeting);
String reply=greeter.sayHi();
assertNotNull("no response received from service",reply);
assertEquals(response2,reply);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testPayloadModeWithSourceData() throws Exception {
URL wsdl=getClass().getResource("/wsdl/hello_world_rpc_lit.wsdl");
assertNotNull(wsdl);
QName serviceName=new QName("http://apache.org/hello_world_rpclit","SOAPServiceProviderRPCLit");
QName portName=new QName("http://apache.org/hello_world_rpclit","SoapPortProviderRPCLit8");
SOAPServiceRPCLit service=new SOAPServiceRPCLit(wsdl,serviceName);
assertNotNull(service);
String addresses[]={"http://localhost:" + PORT + "/SOAPServiceProviderRPCLit/SoapPortProviderRPCLit8","http://localhost:" + PORT + "/SOAPServiceProviderRPCLit/SoapPortProviderRPCLit8-dom","http://localhost:" + PORT + "/SOAPServiceProviderRPCLit/SoapPortProviderRPCLit8-sax","http://localhost:" + PORT + "/SOAPServiceProviderRPCLit/SoapPortProviderRPCLit8-cxfstax","http://localhost:" + PORT + "/SOAPServiceProviderRPCLit/SoapPortProviderRPCLit8-stax","http://localhost:" + PORT + "/SOAPServiceProviderRPCLit/SoapPortProviderRPCLit8-stream"};
String response1=new String("TestGreetMeResponseServerLogicalHandlerServerSOAPHandler");
GreeterRPCLit greeter=service.getPort(portName,GreeterRPCLit.class);
for ( String ad : addresses) {
((BindingProvider)greeter).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,ad);
String greeting=greeter.greetMe("Milestone-0");
assertNotNull("no response received from service " + ad,greeting);
assertEquals("wrong response received from service " + ad,response1,greeting);
}
}
Class: org.apache.cxf.systest.provider.ProviderXMLClientServerTest APIUtilityVerifier UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testDOMSourcePAYLOAD() throws Exception {
URL wsdl=getClass().getResource("/wsdl/hello_world_xml_wrapped.wsdl");
assertNotNull(wsdl);
XMLService service=new XMLService(wsdl,serviceName);
assertNotNull(service);
InputStream is=getClass().getResourceAsStream("/messages/XML_GreetMeDocLiteralReq.xml");
Document doc=StaxUtils.read(is);
DOMSource reqMsg=new DOMSource(doc);
assertNotNull(reqMsg);
Dispatch disp=service.createDispatch(portName,DOMSource.class,Service.Mode.PAYLOAD);
setAddress(disp,ADDRESS);
DOMSource result=disp.invoke(reqMsg);
assertNotNull(result);
Node respDoc=result.getNode();
assertEquals("greetMeResponse",respDoc.getFirstChild().getLocalName());
assertEquals("TestXMLBindingProviderMessage",respDoc.getFirstChild().getTextContent());
is=getClass().getResourceAsStream("/messages/XML_GreetMeDocLiteralReq_invalid.xml");
doc=StaxUtils.read(is);
reqMsg=new DOMSource(doc);
assertNotNull(reqMsg);
disp=service.createDispatch(portName,DOMSource.class,Service.Mode.PAYLOAD);
try {
setAddress(disp,ADDRESS);
result=disp.invoke(reqMsg);
fail("should have a schema validation exception of some sort");
}
catch ( Exception ex) {
}
}
Class: org.apache.cxf.systest.resolver.JarResolverTest APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testResolver() throws Exception {
URL wsdl=getClass().getResource("/wsdl/hello_world.wsdl");
assertNotNull(wsdl);
createBus();
assertNotNull(bus);
ServiceContractResolverRegistryImpl registry=new ServiceContractResolverRegistryImpl();
registry.setBus(bus);
assertNotNull(bus.getExtension(ServiceContractResolverRegistry.class));
JarServiceContractResolver resolver=new JarServiceContractResolver();
registry.register(resolver);
Service service=Service.create(serviceName);
Greeter greeter=service.getPort(portName,Greeter.class);
updateAddressPort(greeter,PORT);
String resp=greeter.sayHi();
assertNotNull(resp);
}
Class: org.apache.cxf.systest.servlet.CXFFilterTest InternalCallVerifier EqualityVerifier
@Test public void testGetServiceList() throws Exception {
ServletUnitClient client=newClient();
client.setExceptionsThrownOnErrorStatus(false);
WebResponse res=client.getResponse(CONTEXT_URL + "/");
WebLink[] links=res.getLinks();
assertEquals("Wrong number of service links",3,links.length);
Set links2=new HashSet();
for ( WebLink l : links) {
links2.add(l.getURLString());
}
assertEquals("text/html",res.getContentType());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testPostInvokeServices() throws Exception {
newClient();
WebRequest req=new PostMethodWebRequest(CONTEXT_URL + "/services/Greeter",getClass().getResourceAsStream("GreeterMessage.xml"),"text/xml; charset=UTF-8");
WebResponse response=newClient().getResponse(req);
assertEquals("text/xml",response.getContentType());
assertEquals(StandardCharsets.UTF_8.name(),response.getCharacterSet());
Document doc=StaxUtils.read(response.getInputStream());
assertNotNull(doc);
addNamespace("h","http://apache.org/hello_world_soap_http/types");
assertValid("/s:Envelope/s:Body",doc);
assertValid("//h:sayHiResponse",doc);
}
Class: org.apache.cxf.systest.servlet.CXFServletTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetWSDL() throws Exception {
ServletUnitClient client=newClient();
client.setExceptionsThrownOnErrorStatus(true);
WebRequest req=new GetMethodQueryWebRequest(CONTEXT_URL + "/services/greeter?wsdl");
WebResponse res=client.getResponse(req);
assertEquals(200,res.getResponseCode());
assertEquals("text/xml",res.getContentType());
Document doc=StaxUtils.read(res.getInputStream());
assertNotNull(doc);
assertValid("//wsdl:operation[@name='greetMe']",doc);
assertValid("//wsdlsoap:address[@location='" + CONTEXT_URL + "/services/greeter']",doc);
}
BooleanVerifier InternalCallVerifier
@Test public void testGetUnformatServiceList() throws Exception {
ServletUnitClient client=newClient();
client.setExceptionsThrownOnErrorStatus(false);
WebResponse res=client.getResponse(CONTEXT_URL + "/services?formatted=false");
assertTrue(res.getText().contains("http://localhost/mycontext/services/greeter3"));
assertTrue(res.getText().contains("http://localhost/mycontext/services/greeter2"));
assertTrue(res.getText().contains("http://localhost/mycontext/services/greeter"));
}
InternalCallVerifier EqualityVerifier
@Test public void testInvalidServiceUrl() throws Exception {
ServletUnitClient client=newClient();
client.setExceptionsThrownOnErrorStatus(false);
WebResponse res=client.getResponse(CONTEXT_URL + "/services/NoSuchService");
assertEquals(404,res.getResponseCode());
assertEquals("text/html",res.getContentType());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetWSDLWithIncludes() throws Exception {
ServletUnitClient client=newClient();
client.setExceptionsThrownOnErrorStatus(true);
WebRequest req=new GetMethodQueryWebRequest(CONTEXT_URL + "/services/greeter3?wsdl");
WebResponse res=client.getResponse(req);
assertEquals(200,res.getResponseCode());
assertEquals("text/xml",res.getContentType());
Document doc=StaxUtils.read(res.getInputStream());
assertNotNull(doc);
assertXPathEquals("//xsd:include/@schemaLocation","http://localhost/mycontext/services/greeter3?xsd=hello_world_includes2.xsd",doc.getDocumentElement());
req=new GetMethodQueryWebRequest(CONTEXT_URL + "/services/greeter3?xsd=hello_world_includes2.xsd");
res=client.getResponse(req);
assertEquals(200,res.getResponseCode());
assertEquals("text/xml",res.getContentType());
doc=StaxUtils.read(res.getInputStream());
assertNotNull(doc);
assertValid("//xsd:complexType[@name='ErrorCode']",doc);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testGetImportedXSD() throws Exception {
ServletUnitClient client=newClient();
client.setExceptionsThrownOnErrorStatus(true);
WebRequest req=new GetMethodQueryWebRequest(CONTEXT_URL + "/services/greeter?wsdl");
WebResponse res=client.getResponse(req);
assertEquals(200,res.getResponseCode());
String text=res.getText();
assertEquals("text/xml",res.getContentType());
assertTrue(text.contains(CONTEXT_URL + "/services/greeter?wsdl=test_import.xsd"));
req=new GetMethodQueryWebRequest(CONTEXT_URL + "/services/greeter?wsdl=test_import.xsd");
res=client.getResponse(req);
assertEquals(200,res.getResponseCode());
text=res.getText();
assertEquals("text/xml",res.getContentType());
assertTrue("the xsd should contain the completType SimpleStruct",text.contains(""));
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetServiceList() throws Exception {
ServletUnitClient client=newClient();
client.setExceptionsThrownOnErrorStatus(false);
WebResponse res=client.getResponse(CONTEXT_URL + "/services");
WebLink[] links=res.getLinks();
assertEquals("Wrong number of service links",6,links.length);
Set links2=new HashSet();
for ( WebLink l : links) {
links2.add(l.getURLString());
}
assertTrue(links2.contains(CONTEXT_URL + "/services/greeter?wsdl"));
assertTrue(links2.contains(CONTEXT_URL + "/services/greeter2?wsdl"));
assertTrue(links2.contains("http://cxf.apache.org/MyGreeter?wsdl"));
assertEquals("text/html",res.getContentType());
res=client.getResponse(CONTEXT_URL + "/services/");
links=res.getLinks();
links2.clear();
for ( WebLink l : links) {
links2.add(l.getURLString());
}
assertEquals("Wrong number of service links",6,links.length);
assertTrue(links2.contains(CONTEXT_URL + "/services/greeter?wsdl"));
assertTrue(links2.contains(CONTEXT_URL + "/services/greeter2?wsdl"));
assertTrue(links2.contains("http://cxf.apache.org/MyGreeter?wsdl"));
assertEquals("text/html",res.getContentType());
assertNotNull(BusFactory.getDefaultBus(false));
}
BooleanVerifier InternalCallVerifier
@Test public void testServiceListWithLoopAddress() throws Exception {
ServletUnitClient client=newClient();
client.setExceptionsThrownOnErrorStatus(false);
WebResponse res=client.getResponse(CONTEXT_URL + "/services");
assertTrue(res.getText().contains("http://localhost/mycontext/services/greeter3"));
assertTrue(res.getText().contains("http://localhost/mycontext/services/greeter2"));
assertTrue(res.getText().contains("http://localhost/mycontext/services/greeter"));
WebRequest req=new GetMethodQueryWebRequest(CONTEXT_URL + "/services/greeter?wsdl");
res=client.getResponse(req);
req=new GetMethodQueryWebRequest(CONTEXT_URL + "/services/greeter2?wsdl");
res=client.getResponse(req);
req=new GetMethodQueryWebRequest(CONTEXT_URL + "/services/greeter3?wsdl");
res=client.getResponse(req);
String loopAddr="http://127.0.0.1/mycontext";
res=client.getResponse(loopAddr + "/services");
assertFalse(res.getText().contains("http://127.0.0.1/mycontext/serviceshttp://localhost/mycontext/services/greeter"));
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetWSDLWithXMLBinding() throws Exception {
ServletUnitClient client=newClient();
client.setExceptionsThrownOnErrorStatus(true);
WebRequest req=new GetMethodQueryWebRequest(CONTEXT_URL + "/services/greeter2?wsdl");
WebResponse res=client.getResponse(req);
assertEquals(200,res.getResponseCode());
assertEquals("text/xml",res.getContentType());
Document doc=StaxUtils.read(res.getInputStream());
assertNotNull(doc);
addNamespace("http","http://schemas.xmlsoap.org/wsdl/http/");
assertValid("//wsdl:operation[@name='greetMe']",doc);
NodeList addresses=assertValid("//http:address/@location",doc);
boolean found=true;
for (int i=0; i < addresses.getLength(); i++) {
String address=addresses.item(i).getLocalName();
if (address.startsWith("http://localhost") && address.endsWith("/services/greeter2")) {
found=true;
break;
}
}
assertTrue(found);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetWSDLWithMultiplePublishedEndpointUrl() throws Exception {
ServletUnitClient client=newClient();
client.setExceptionsThrownOnErrorStatus(true);
WebRequest req=new GetMethodQueryWebRequest(CONTEXT_URL + "/services/greeter5?wsdl");
WebResponse res=client.getResponse(req);
assertEquals(200,res.getResponseCode());
assertEquals("text/xml",res.getContentType());
Document doc=StaxUtils.read(res.getInputStream());
assertNotNull(doc);
WSDLReader wsdlReader=WSDLFactory.newInstance().newWSDLReader();
wsdlReader.setFeature("javax.wsdl.verbose",false);
assertValid("//wsdl:service[@name='SOAPService']/wsdl:port[@name='SoapPort']/wsdlsoap:address[@location='" + "http://cxf.apache.org/publishedEndpointUrl1']",doc);
assertValid("//wsdl:service[@name='SOAPService']/wsdl:port[@name='SoapPort1']/wsdlsoap:address[@location='" + "http://cxf.apache.org/publishedEndpointUrl2']",doc);
}
Class: org.apache.cxf.systest.servlet.ExternalServicesServletTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testPostInvokeServices() throws Exception {
newClient();
WebRequest req=new PostMethodWebRequest(CONTEXT_URL + "/greeter",getClass().getResourceAsStream("GreeterMessage.xml"),"text/xml; charset=UTF-8");
WebResponse response=newClient().getResponse(req);
assertEquals("text/xml",response.getContentType());
assertEquals(StandardCharsets.UTF_8.name(),response.getCharacterSet());
Document doc=StaxUtils.read(response.getInputStream());
assertNotNull(doc);
addNamespace("h","http://apache.org/hello_world_soap_http/types");
assertValid("/s:Envelope/s:Body",doc);
assertValid("//h:sayHiResponse",doc);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testGetServiceList() throws Exception {
ServletUnitClient client=newClient();
client.setExceptionsThrownOnErrorStatus(false);
WebResponse res=client.getResponse(CONTEXT_URL + "/");
WebLink[] links=res.getLinks();
assertEquals("Wrong number of service links",6,links.length);
Set links2=new HashSet();
for ( WebLink l : links) {
links2.add(l.getURLString());
}
assertTrue(links2.contains(FORCED_BASE_ADDRESS + "/greeter?wsdl"));
assertTrue(links2.contains(FORCED_BASE_ADDRESS + "/greeter2?wsdl"));
assertEquals("text/html",res.getContentType());
}
Class: org.apache.cxf.systest.servlet.JsFrontEndServletTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testPostInvokeServices() throws Exception {
WebRequest req=new PostMethodWebRequest(CONTEXT_URL + "/services/Greeter",getClass().getResourceAsStream("GreeterMessage.xml"),"text/xml; charset=UTF-8");
WebResponse response=newClient().getResponse(req);
assertEquals("text/xml",response.getContentType());
Document doc=StaxUtils.read(response.getInputStream());
assertNotNull(doc);
addNamespace("h","http://apache.org/hello_world_soap_http/types");
assertValid("/s:Envelope/s:Body",doc);
assertValid("//h:sayHiResponse",doc);
assertValid("//h:responseType",doc);
}
Class: org.apache.cxf.systest.servlet.NoSpringServletClientTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBasicConnection() throws Exception {
SOAPService service=new SOAPService(new URL(serviceURL + "Greeter?wsdl"));
Greeter greeter=service.getPort(portName,Greeter.class);
try {
String reply=greeter.greetMe("test");
assertNotNull("no response received from service",reply);
assertEquals("Hello test",reply);
reply=greeter.sayHi();
assertNotNull("no response received from service",reply);
assertEquals("Bonjour",reply);
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
InternalCallVerifier EqualityVerifier
@Test public void testHelloService() throws Exception {
JaxWsProxyFactoryBean cpfb=new JaxWsProxyFactoryBean();
String address=serviceURL + "Hello";
cpfb.setServiceClass(Hello.class);
cpfb.setAddress(address);
Hello hello=(Hello)cpfb.create();
String reply=hello.sayHi(" Willem");
assertEquals("Get the wrongreply ",reply,"get Willem");
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testGetServiceList() throws Exception {
WebConversation client=new WebConversation();
WebResponse res=client.getResponse(serviceURL + "/services");
WebLink[] links=res.getLinks();
Set s=new HashSet();
for ( WebLink l : links) {
s.add(l.getURLString());
}
assertEquals("There should be 3 links for the service",3,links.length);
assertTrue(s.contains(serviceURL + "Greeter?wsdl"));
assertTrue(s.contains(serviceURL + "Hello?wsdl"));
assertTrue(s.contains(serviceURL + "?wsdl"));
assertEquals("text/html",res.getContentType());
}
Class: org.apache.cxf.systest.servlet.SpringAutoPublishServletTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetWSDL() throws Exception {
ServletUnitClient client=newClient();
client.setExceptionsThrownOnErrorStatus(true);
WebRequest req=new GetMethodQueryWebRequest(CONTEXT_URL + "/services/SOAPService?wsdl");
WebResponse res=client.getResponse(req);
assertEquals(200,res.getResponseCode());
assertEquals("text/xml",res.getContentType());
Document doc=StaxUtils.read(res.getInputStream());
assertNotNull(doc);
assertValid("//wsdl:operation[@name='greetMe']",doc);
assertValid("//wsdlsoap:address[@location='" + CONTEXT_URL + "/services/SOAPService']",doc);
req=new GetMethodQueryWebRequest(CONTEXT_URL + "/services/DerivedGreeterService?wsdl");
res=client.getResponse(req);
assertEquals(200,res.getResponseCode());
assertEquals("text/xml",res.getContentType());
doc=StaxUtils.read(res.getInputStream());
assertNotNull(doc);
assertValid("//wsdl:operation[@name='greetMe']",doc);
assertValid("//wsdlsoap:address" + "[@location='http://localhost/mycontext/services/DerivedGreeterService']",doc);
}
Class: org.apache.cxf.systest.servlet.SpringServletTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetWSDL() throws Exception {
ServletUnitClient client=newClient();
client.setExceptionsThrownOnErrorStatus(true);
WebRequest req=new GetMethodQueryWebRequest(CONTEXT_URL + "/services/Greeter?wsdl");
WebResponse res=client.getResponse(req);
assertEquals(200,res.getResponseCode());
assertEquals("text/xml",res.getContentType());
Document doc=StaxUtils.read(res.getInputStream());
assertNotNull(doc);
assertValid("//wsdl:operation[@name='greetMe']",doc);
assertValid("//wsdlsoap:address[@location='" + CONTEXT_URL + "/services/Greeter']",doc);
req=new GetMethodQueryWebRequest(CONTEXT_URL + "/services/Greeter2?wsdl");
res=client.getResponse(req);
assertEquals(200,res.getResponseCode());
assertEquals("text/xml",res.getContentType());
doc=StaxUtils.read(res.getInputStream());
assertNotNull(doc);
assertValid("//wsdl:operation[@name='greetMe']",doc);
assertValid("//wsdlsoap:address[@location='http://cxf.apache.org/Greeter']",doc);
Endpoint.publish("/services/Greeter3",new org.apache.hello_world_soap_http.GreeterImpl());
req=new GetMethodQueryWebRequest(CONTEXT_URL + "/services/Greeter3?wsdl");
res=client.getResponse(req);
assertEquals(200,res.getResponseCode());
assertEquals("text/xml",res.getContentType());
doc=StaxUtils.read(res.getInputStream());
assertNotNull(doc);
assertValid("//wsdl:operation[@name='greetMe']",doc);
assertValid("//wsdlsoap:address[@location='" + CONTEXT_URL + "/services/Greeter3']",doc);
}
Class: org.apache.cxf.systest.simple.SimpleFrontendTest BooleanVerifier InternalCallVerifier
@Test public void testGetWSDL() throws Exception {
GetMethod getMethod=new GetMethod("http://localhost:" + PORT1 + "/test11?wsdl");
HttpClient httpClient=new HttpClient();
httpClient.executeMethod(getMethod);
String response=getMethod.getResponseBodyAsString();
assertFalse(response.indexOf("import") >= 0);
assertFalse(response.indexOf("?wsdl?wsdl") >= 0);
}
Class: org.apache.cxf.systest.soap.SoapActionTest UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testRPCLitSoapActionSpoofing() throws Exception {
JaxWsProxyFactoryBean pf=new JaxWsProxyFactoryBean();
pf.setServiceClass(WrappedGreeter.class);
pf.setAddress(add15);
pf.setBus(bus);
WrappedGreeter greeter=(WrappedGreeter)pf.create();
assertEquals("sayHi",greeter.sayHiRequestWrapped("test"));
assertEquals("sayHi2",greeter.sayHiRequest2Wrapped("test"));
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_USE_PROPERTY,"true");
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_URI_PROPERTY,"SAY_HI_2");
try {
greeter.sayHiRequestWrapped("test");
fail("Failure expected on spoofing attack");
}
catch ( Exception ex) {
}
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_USE_PROPERTY,"true");
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_URI_PROPERTY,"SAY_HI_1");
try {
greeter.sayHiRequest2Wrapped("test");
fail("Failure expected on spoofing attack");
}
catch ( Exception ex) {
}
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_USE_PROPERTY,"true");
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_URI_PROPERTY,"SAY_HI_UNKNOWN");
try {
greeter.sayHiRequestWrapped("test");
fail("Failure expected on spoofing attack");
}
catch ( Exception ex) {
}
}
UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testWrappedEncodedSoapActionSpoofing() throws Exception {
JaxWsProxyFactoryBean pf=new JaxWsProxyFactoryBean();
pf.setServiceClass(WrappedGreeter.class);
pf.setAddress(add17);
pf.setBus(bus);
WrappedGreeter greeter=(WrappedGreeter)pf.create();
assertEquals("sayHi",greeter.sayHiRequestWrapped("test"));
assertEquals("sayHi2",greeter.sayHiRequest2Wrapped("test"));
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_USE_PROPERTY,"true");
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_URI_PROPERTY,"SAY_HI_2");
try {
greeter.sayHiRequestWrapped("test");
fail("Failure expected on spoofing attack");
}
catch ( Exception ex) {
}
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_USE_PROPERTY,"true");
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_URI_PROPERTY,"SAY_HI_1");
try {
greeter.sayHiRequest2Wrapped("test");
fail("Failure expected on spoofing attack");
}
catch ( Exception ex) {
}
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_USE_PROPERTY,"true");
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_URI_PROPERTY,"SAY_HI_UNKNOWN");
try {
greeter.sayHiRequestWrapped("test");
fail("Failure expected on spoofing attack");
}
catch ( Exception ex) {
}
}
UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testWrappedSoap12ActionSpoofing() throws Exception {
JaxWsProxyFactoryBean pf=new JaxWsProxyFactoryBean();
pf.setServiceClass(WrappedGreeter.class);
pf.setAddress(add14);
SoapBindingConfiguration config=new SoapBindingConfiguration();
config.setVersion(Soap12.getInstance());
pf.setBindingConfig(config);
pf.setBus(bus);
WrappedGreeter greeter=(WrappedGreeter)pf.create();
assertEquals("sayHi",greeter.sayHiRequestWrapped("test"));
assertEquals("sayHi2",greeter.sayHiRequest2Wrapped("test"));
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_USE_PROPERTY,"true");
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_URI_PROPERTY,"SAY_HI_2");
try {
greeter.sayHiRequestWrapped("test");
fail("Failure expected on spoofing attack");
}
catch ( Exception ex) {
}
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_USE_PROPERTY,"true");
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_URI_PROPERTY,"SAY_HI_1");
try {
greeter.sayHiRequest2Wrapped("test");
fail("Failure expected on spoofing attack");
}
catch ( Exception ex) {
}
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_USE_PROPERTY,"true");
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_URI_PROPERTY,"SAY_HI_UNKNOWN");
try {
greeter.sayHiRequestWrapped("test");
fail("Failure expected on spoofing attack");
}
catch ( Exception ex) {
}
}
InternalCallVerifier EqualityVerifier
@Test public void testEndpoint() throws Exception {
JaxWsProxyFactoryBean pf=new JaxWsProxyFactoryBean();
pf.setServiceClass(Greeter.class);
pf.setAddress(add11);
pf.setBus(bus);
Greeter greeter=(Greeter)pf.create();
assertEquals("sayHi",greeter.sayHi("test"));
assertEquals("sayHi2",greeter.sayHi2("test"));
}
InternalCallVerifier EqualityVerifier
@Test public void testSoap12Endpoint() throws Exception {
JaxWsProxyFactoryBean pf=new JaxWsProxyFactoryBean();
pf.setServiceClass(Greeter.class);
pf.setAddress(add12);
SoapBindingConfiguration config=new SoapBindingConfiguration();
config.setVersion(Soap12.getInstance());
pf.setBindingConfig(config);
pf.setBus(bus);
Greeter greeter=(Greeter)pf.create();
assertEquals("sayHi",greeter.sayHi("test"));
assertEquals("sayHi2",greeter.sayHi2("test"));
}
UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testBareSoapActionSpoofing() throws Exception {
JaxWsProxyFactoryBean pf=new JaxWsProxyFactoryBean();
pf.setServiceClass(Greeter.class);
pf.setAddress(add11);
pf.setBus(bus);
Greeter greeter=(Greeter)pf.create();
assertEquals("sayHi",greeter.sayHi("test"));
assertEquals("sayHi2",greeter.sayHi2("test"));
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_USE_PROPERTY,"true");
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_URI_PROPERTY,"SAY_HI_2");
try {
greeter.sayHi("test");
fail("Failure expected on spoofing attack");
}
catch ( Exception ex) {
}
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_USE_PROPERTY,"true");
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_URI_PROPERTY,"SAY_HI_1");
try {
greeter.sayHi2("test");
fail("Failure expected on spoofing attack");
}
catch ( Exception ex) {
}
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_USE_PROPERTY,"true");
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_URI_PROPERTY,"SAY_HI_UNKNOWN");
try {
greeter.sayHi("test");
fail("Failure expected on spoofing attack");
}
catch ( Exception ex) {
}
}
UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testRPCEncodedSoapActionSpoofing() throws Exception {
JaxWsProxyFactoryBean pf=new JaxWsProxyFactoryBean();
pf.setServiceClass(WrappedGreeter.class);
pf.setAddress(add16);
pf.setBus(bus);
WrappedGreeter greeter=(WrappedGreeter)pf.create();
assertEquals("sayHi",greeter.sayHiRequestWrapped("test"));
assertEquals("sayHi2",greeter.sayHiRequest2Wrapped("test"));
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_USE_PROPERTY,"true");
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_URI_PROPERTY,"SAY_HI_2");
try {
greeter.sayHiRequestWrapped("test");
fail("Failure expected on spoofing attack");
}
catch ( Exception ex) {
}
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_USE_PROPERTY,"true");
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_URI_PROPERTY,"SAY_HI_1");
try {
greeter.sayHiRequest2Wrapped("test");
fail("Failure expected on spoofing attack");
}
catch ( Exception ex) {
}
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_USE_PROPERTY,"true");
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_URI_PROPERTY,"SAY_HI_UNKNOWN");
try {
greeter.sayHiRequestWrapped("test");
fail("Failure expected on spoofing attack");
}
catch ( Exception ex) {
}
}
UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testWrappedSoapActionSpoofing() throws Exception {
JaxWsProxyFactoryBean pf=new JaxWsProxyFactoryBean();
pf.setServiceClass(WrappedGreeter.class);
pf.setAddress(add13);
pf.setBus(bus);
WrappedGreeter greeter=(WrappedGreeter)pf.create();
assertEquals("sayHi",greeter.sayHiRequestWrapped("test"));
assertEquals("sayHi2",greeter.sayHiRequest2Wrapped("test"));
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_USE_PROPERTY,"true");
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_URI_PROPERTY,"SAY_HI_2");
try {
greeter.sayHiRequestWrapped("test");
fail("Failure expected on spoofing attack");
}
catch ( Exception ex) {
}
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_USE_PROPERTY,"true");
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_URI_PROPERTY,"SAY_HI_1");
try {
greeter.sayHiRequest2Wrapped("test");
fail("Failure expected on spoofing attack");
}
catch ( Exception ex) {
}
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_USE_PROPERTY,"true");
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_URI_PROPERTY,"SAY_HI_UNKNOWN");
try {
greeter.sayHiRequestWrapped("test");
fail("Failure expected on spoofing attack");
}
catch ( Exception ex) {
}
}
UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testBareSoap12ActionSpoofing() throws Exception {
JaxWsProxyFactoryBean pf=new JaxWsProxyFactoryBean();
pf.setServiceClass(Greeter.class);
pf.setAddress(add12);
SoapBindingConfiguration config=new SoapBindingConfiguration();
config.setVersion(Soap12.getInstance());
pf.setBindingConfig(config);
pf.setBus(bus);
Greeter greeter=(Greeter)pf.create();
assertEquals("sayHi",greeter.sayHi("test"));
assertEquals("sayHi2",greeter.sayHi2("test"));
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_USE_PROPERTY,"true");
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_URI_PROPERTY,"SAY_HI_2");
try {
greeter.sayHi("test");
fail("Failure expected on spoofing attack");
}
catch ( Exception ex) {
}
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_USE_PROPERTY,"true");
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_URI_PROPERTY,"SAY_HI_1");
try {
greeter.sayHi2("test");
fail("Failure expected on spoofing attack");
}
catch ( Exception ex) {
}
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_USE_PROPERTY,"true");
((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_URI_PROPERTY,"SAY_HI_UNKNOWN");
try {
greeter.sayHi("test");
fail("Failure expected on spoofing attack");
}
catch ( Exception ex) {
}
}
Class: org.apache.cxf.systest.soap12.Soap12ClientServerTest UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testPingMeFault() throws Exception {
Greeter greeter=getGreeter();
try {
greeter.pingMe();
fail("Should throw Exception!");
}
catch ( PingMeFault ex) {
FaultDetail detail=ex.getFaultInfo();
assertEquals((short)2,detail.getMajor());
assertEquals((short)1,detail.getMinor());
assertEquals("PingMeFault raised by server",ex.getMessage());
}
}
IterativeVerifier InternalCallVerifier EqualityVerifier
@Test public void testBasicConnection() throws Exception {
Greeter greeter=getGreeter();
for (int i=0; i < 5; i++) {
String echo=greeter.sayHi();
assertEquals("Bonjour",echo);
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSayHiSoap12ToSoap11() throws Exception {
HttpURLConnection httpConnection=getHttpConnection("http://localhost:" + PORT + "/SoapContext/Soap11Port/sayHi");
httpConnection.setDoOutput(true);
InputStream reqin=Soap12ClientServerTest.class.getResourceAsStream("sayHiSOAP12Req.xml");
assertNotNull("could not load test data",reqin);
httpConnection.setRequestMethod("POST");
httpConnection.addRequestProperty("Content-Type","text/xml;charset=utf-8");
OutputStream reqout=httpConnection.getOutputStream();
IOUtils.copy(reqin,reqout);
reqout.close();
assertEquals(500,httpConnection.getResponseCode());
InputStream respin=httpConnection.getErrorStream();
assertNotNull(respin);
assertEquals("text/xml;charset=utf-8",stripSpaces(httpConnection.getContentType().toLowerCase()));
Document doc=StaxUtils.read(respin);
assertNotNull(doc);
Map ns=new HashMap();
ns.put("soap11",Soap11.SOAP_NAMESPACE);
XPathUtils xu=new XPathUtils(ns);
Node fault=(Node)xu.getValue("/soap11:Envelope/soap11:Body/soap11:Fault",doc,XPathConstants.NODE);
assertNotNull(fault);
String codev=(String)xu.getValue("//faultcode/text()",fault,XPathConstants.STRING);
assertNotNull(codev);
assertTrue("VersionMismatch expected",codev.endsWith("VersionMismatch"));
}
Class: org.apache.cxf.systest.soap_udp.SoapUDPTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSOAPUDP(){
BusFactory.setThreadDefaultBus(staticBus);
Service service=Service.create(serviceName);
service.addPort(localPortName,"http://schemas.xmlsoap.org/soap/","soap.udp://localhost:" + PORT);
Greeter greeter=service.getPort(localPortName,Greeter.class);
String reply=greeter.greetMe("test");
assertEquals("Hello test",reply);
reply=greeter.sayHi();
assertNotNull("no response received from service",reply);
assertEquals("Bonjour",reply);
}
Class: org.apache.cxf.systest.soapfault.details.Soap11ClientServerTest UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testPingMeFault() throws Exception {
Greeter greeter=getGreeter();
try {
greeter.pingMe();
fail("Should throw Exception!");
}
catch ( PingMeFault ex) {
FaultDetail detail=ex.getFaultInfo();
assertEquals((short)2,detail.getMajor());
assertEquals((short)1,detail.getMinor());
assertEquals("PingMeFault raised by server",ex.getMessage());
StackTraceElement[] element=ex.getStackTrace();
assertEquals("org.apache.cxf.systest.soapfault.details.GreeterImpl11",element[0].getClassName());
}
}
Class: org.apache.cxf.systest.soapfault.details.Soap12ClientServerTest UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testPingMeFault() throws Exception {
Greeter greeter=getGreeter();
try {
greeter.pingMe();
fail("Should throw Exception!");
}
catch ( PingMeFault ex) {
FaultDetail detail=ex.getFaultInfo();
assertEquals((short)2,detail.getMajor());
assertEquals((short)1,detail.getMinor());
assertEquals("PingMeFault raised by server",ex.getMessage());
StackTraceElement[] element=ex.getStackTrace();
assertEquals("org.apache.cxf.systest.soapfault.details.GreeterImpl12",element[0].getClassName());
}
}
Class: org.apache.cxf.systest.soapheader.HeaderClientServerTest InternalCallVerifier EqualityVerifier
@Test public void testBasicConnection() throws Exception {
Pizza port=getPort();
updateAddressPort(port,PORT);
OrderPizzaType req=new OrderPizzaType();
ToppingsListType t=new ToppingsListType();
t.getTopping().add("test");
req.setToppings(t);
CallerIDHeaderType header=new CallerIDHeaderType();
header.setName("mao");
header.setPhoneNumber("108");
OrderPizzaResponseType res=port.orderPizza(req,header);
assertEquals(208,res.getMinutesUntilReady());
}
InternalCallVerifier EqualityVerifier
@Test public void testBasicConnectionNoHeader() throws Exception {
PizzaNoHeader port=getPortNoHeader();
updateAddressPort(port,PORT);
OrderPizzaType req=new OrderPizzaType();
ToppingsListType t=new ToppingsListType();
t.getTopping().add("NoHeader!");
t.getTopping().add("test");
req.setToppings(t);
OrderPizzaResponseType res=port.orderPizza(req);
assertEquals(100,res.getMinutesUntilReady());
}
Class: org.apache.cxf.systest.source.ClientServerSourceTest UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCallFromClient() throws Exception {
SpringBusFactory factory=new SpringBusFactory();
Bus bus=factory.createBus("org/apache/cxf/systest/source/cxf.xml");
BusFactory.setDefaultBus(bus);
URL wsdl=this.getClass().getResource("/wsdl_systest_databinding/source/hello_world.wsdl");
assertNotNull("We should have found the WSDL here. ",wsdl);
SOAPService ss=new SOAPService(wsdl,SERVICE_NAME);
Greeter port=ss.getSoapPort();
updateAddressPort(port,WSDL_PORT);
ClientProxy.getClient(port).getInInterceptors().add(new LoggingInInterceptor());
ClientProxy.getClient(port).getOutInterceptors().add(new LoggingOutInterceptor());
Document doc=DOMUtils.newDocument();
doc.appendChild(doc.createElementNS("http://apache.org/hello_world_soap_http_source/source/types","ns1:sayHi"));
DOMSource ds=new DOMSource(doc);
DOMSource resp=port.sayHi(ds);
assertEquals("We should get the right response","Bonjour",DOMUtils.getContent(getElement(resp.getNode().getFirstChild().getFirstChild())));
doc=DOMUtils.newDocument();
Element el=doc.createElementNS("http://apache.org/hello_world_soap_http_source/source/types","ns1:greetMe");
Element el2=doc.createElementNS("http://apache.org/hello_world_soap_http_source/source/types","ns1:requestType");
el2.appendChild(doc.createTextNode("Willem"));
el.appendChild(el2);
doc.appendChild(el);
ds=new DOMSource(doc);
resp=port.greetMe(ds);
assertEquals("We should get the right response","Hello Willem",DOMUtils.getContent(DOMUtils.getFirstElement(getElement(resp.getNode()))));
try {
doc=DOMUtils.newDocument();
el=doc.createElementNS("http://apache.org/hello_world_soap_http_source/source/types","ns1:greetMe");
el2=doc.createElementNS("http://apache.org/hello_world_soap_http_source/source/types","ns1:requestType");
el2.appendChild(doc.createTextNode("fault"));
el.appendChild(el2);
doc.appendChild(el);
ds=new DOMSource(doc);
port.greetMe(ds);
fail("Should have been a fault");
}
catch ( GreetMeFault ex) {
assertEquals("Some fault detail",DOMUtils.getContent(getElement(ex.getFaultInfo().getNode())));
}
}
Class: org.apache.cxf.systest.stringarray.StringArrayTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testStringArrayList() throws Exception {
SpringBusFactory factory=new SpringBusFactory();
Bus bus=factory.createBus();
BusFactory.setDefaultBus(bus);
setBus(bus);
StringWriter swin=new java.io.StringWriter();
java.io.PrintWriter pwin=new java.io.PrintWriter(swin);
LoggingInInterceptor logIn=new LoggingInInterceptor(pwin);
StringWriter swout=new java.io.StringWriter();
java.io.PrintWriter pwout=new java.io.PrintWriter(swout);
LoggingOutInterceptor logOut=new LoggingOutInterceptor(pwout);
getBus().getInInterceptors().add(logIn);
getBus().getOutInterceptors().add(logOut);
SOAPServiceRPCLit service=new SOAPServiceRPCLit();
StringListTest port=service.getSoapPortRPCLit();
updateAddressPort(port,PORT);
String[] strs=new String[]{"org","apache","cxf"};
String[] res=port.stringListTest(strs);
assertArrayEquals(strs,res);
assertTrue("Request message is not marshalled correctly and @XmlList does not take effect",swout.toString().indexOf("org apache cxf ") > -1);
assertTrue("Response message is not marshalled correctly and @XmlList does not take effect",swin.toString().indexOf("org apache cxf ") > -1);
}
Class: org.apache.cxf.systest.sts.itests.unit.STSUnitTest APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testBearerSAML2Token() throws URISyntaxException, Exception {
Bus bus=BusFactory.getDefaultBus();
SecurityToken token=requestSecurityToken(SAML2_TOKEN_TYPE,BEARER_KEYTYPE,bus,STS_ENDPOINT);
Assert.assertTrue(SAML2_TOKEN_TYPE.equals(token.getTokenType()));
Assert.assertTrue(token.getToken() != null);
List results=processToken(token);
Assert.assertTrue(results != null && results.size() == 1);
SamlAssertionWrapper assertion=(SamlAssertionWrapper)results.get(0).get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
Assert.assertTrue(assertion != null);
Assert.assertTrue(assertion.getSaml1() == null && assertion.getSaml2() != null);
Assert.assertTrue(assertion.isSigned());
List methods=assertion.getConfirmationMethods();
String confirmMethod=null;
if (methods != null && methods.size() > 0) {
confirmMethod=methods.get(0);
}
Assert.assertTrue(confirmMethod.contains("bearer"));
bus.shutdown(true);
}
Class: org.apache.cxf.systest.swa.ClientServerSwaTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier PublicFieldVerifier HybridVerifier
@Test public void testSwaNoMimeCodeGen() throws Exception {
org.apache.cxf.swa_nomime.SwAService service=new org.apache.cxf.swa_nomime.SwAService();
org.apache.cxf.swa_nomime.SwAServiceInterface port=service.getSwAServiceHttpPort();
setAddress(port,"http://localhost:" + serverPort + "/swa-nomime");
Holder textHolder=new Holder("Hi");
Holder data=new Holder("foobar".getBytes());
port.echoData(textHolder,data);
String string=IOUtils.newStringFromBytes(data.value);
assertEquals("testfoobar",string);
assertEquals("Hi",textHolder.value);
URL url1=this.getClass().getResource("resources/attach.text");
URL url2=this.getClass().getResource("resources/attach.html");
URL url3=this.getClass().getResource("resources/attach.xml");
URL url4=this.getClass().getResource("resources/attach.jpeg1");
URL url5=this.getClass().getResource("resources/attach.jpeg2");
Holder attach1=new Holder(IOUtils.toString(url1.openStream()));
Holder attach2=new Holder(IOUtils.toString(url2.openStream()));
Holder attach3=new Holder(IOUtils.toString(url3.openStream()));
Holder attach4=new Holder(IOUtils.readBytesFromStream(url4.openStream()));
Holder attach5=new Holder(IOUtils.readBytesFromStream(url5.openStream()));
org.apache.cxf.swa_nomime.types.VoidRequest request=new org.apache.cxf.swa_nomime.types.VoidRequest();
org.apache.cxf.swa_nomime.types.OutputResponseAll response=port.echoAllAttachmentTypes(request,attach1,attach2,attach3,attach4,attach5);
assertNotNull(response);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testSwaTypesWithDispatchAPI() throws Exception {
URL url1=this.getClass().getResource("resources/attach.text");
URL url2=this.getClass().getResource("resources/attach.html");
URL url3=this.getClass().getResource("resources/attach.xml");
URL url4=this.getClass().getResource("resources/attach.jpeg1");
URL url5=this.getClass().getResource("resources/attach.jpeg2");
byte[] bytes=IOUtils.readBytesFromStream(url1.openStream());
byte[] bigBytes=new byte[bytes.length * 50];
for (int x=0; x < 50; x++) {
System.arraycopy(bytes,0,bigBytes,x * bytes.length,bytes.length);
}
DataHandler dh1=new DataHandler(new ByteArrayDataSource(bigBytes,"text/plain"));
DataHandler dh2=new DataHandler(url2);
DataHandler dh3=new DataHandler(url3);
DataHandler dh4=new DataHandler(url4);
DataHandler dh5=new DataHandler(url5);
SwAService service=new SwAService();
Dispatch disp=service.createDispatch(SwAService.SwAServiceHttpPort,SOAPMessage.class,Service.Mode.MESSAGE);
setAddress(disp,"http://localhost:" + serverPort + "/swa");
SOAPMessage msg=MessageFactory.newInstance().createMessage();
SOAPBody body=msg.getSOAPPart().getEnvelope().getBody();
body.addBodyElement(new QName("http://cxf.apache.org/swa/types","VoidRequest"));
AttachmentPart att=msg.createAttachmentPart(dh1);
att.setContentId("");
msg.addAttachmentPart(att);
att=msg.createAttachmentPart(dh2);
att.setContentId("");
msg.addAttachmentPart(att);
att=msg.createAttachmentPart(dh3);
att.setContentId("");
msg.addAttachmentPart(att);
att=msg.createAttachmentPart(dh4);
att.setContentId("");
msg.addAttachmentPart(att);
att=msg.createAttachmentPart(dh5);
att.setContentId("");
msg.addAttachmentPart(att);
msg=disp.invoke(msg);
assertEquals(5,msg.countAttachments());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSwaTypes() throws Exception {
SwAService service=new SwAService();
SwAServiceInterface port=service.getSwAServiceHttpPort();
setAddress(port,"http://localhost:" + serverPort + "/swa");
URL url1=this.getClass().getResource("resources/attach.text");
URL url2=this.getClass().getResource("resources/attach.html");
URL url3=this.getClass().getResource("resources/attach.xml");
URL url4=this.getClass().getResource("resources/attach.jpeg1");
URL url5=this.getClass().getResource("resources/attach.jpeg2");
DataHandler dh1=new DataHandler(url1);
DataHandler dh2=new DataHandler(url2);
DataHandler dh3=new DataHandler(url3);
Holder attach1=new Holder();
attach1.value=dh1;
Holder attach2=new Holder();
attach2.value=dh2;
Holder attach3=new Holder();
attach3.value=new StreamSource(dh3.getInputStream());
Holder attach4=new Holder();
Holder attach5=new Holder();
attach4.value=ImageIO.read(url4);
attach5.value=ImageIO.read(url5);
VoidRequest request=new VoidRequest();
OutputResponseAll response=port.echoAllAttachmentTypes(request,attach1,attach2,attach3,attach4,attach5);
assertNotNull(response);
Map,?> map=CastUtils.cast((Map,?>)((BindingProvider)port).getResponseContext().get(MessageContext.INBOUND_MESSAGE_ATTACHMENTS));
assertNotNull(map);
assertEquals(5,map.size());
}
Class: org.apache.cxf.systest.transform.feature.TransformFeatureTest APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testClientInTransformation(){
Service service=Service.create(SERVICE_NAME);
String endpoint="http://localhost:" + PORT + "/EchoContext/EchoPort";
service.addPort(PORT_NAME,SOAPBinding.SOAP11HTTP_BINDING,endpoint);
Echo port=service.getPort(PORT_NAME,Echo.class);
Client client=ClientProxy.getClient(port);
XSLTInInterceptor inInterceptor=new XSLTInInterceptor(XSLT_RESPONSE_PATH);
client.getInInterceptors().add(inInterceptor);
String response=port.echo("test");
Assert.assertTrue(response.contains(TRANSFORMED_CONSTANT));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testClientOutTransformation(){
Service service=Service.create(SERVICE_NAME);
String endpoint="http://localhost:" + PORT + "/EchoContext/EchoPort";
service.addPort(PORT_NAME,SOAPBinding.SOAP11HTTP_BINDING,endpoint);
Echo port=service.getPort(PORT_NAME,Echo.class);
Client client=ClientProxy.getClient(port);
XSLTOutInterceptor outInterceptor=new XSLTOutInterceptor(XSLT_REQUEST_PATH);
client.getOutInterceptors().add(outInterceptor);
String response=port.echo("test");
Assert.assertTrue("Request was not transformed",response.contains(TRANSFORMED_CONSTANT));
}
Class: org.apache.cxf.systest.type_substitution.TypeSubClientServerTest APIUtilityVerifier BranchVerifier UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBasicConnection() throws Exception {
CarDealer dealer=getCardealer();
List cars=dealer.getSedans("porsche");
assertEquals(2,cars.size());
Porsche car=(Porsche)cars.get(0);
assertNotNull(car);
if (car != null && "Porsche".equals(car.getMake()) && "Boxster".equals(car.getModel()) && "1998".equals(car.getYear()) && "white".equals(car.getColor())) {
}
else {
fail("Get the wrong car!");
}
Porsche oldCar=new Porsche();
oldCar.setMake("Porsche");
oldCar.setColor("white");
oldCar.setModel("GT2000");
oldCar.setYear("2000");
Porsche newCar=(Porsche)dealer.tradeIn(oldCar);
assertNotNull(newCar);
if (newCar != null && "Porsche".equals(newCar.getMake()) && "911GT3".equals(newCar.getModel()) && "2007".equals(newCar.getYear()) && "black".equals(newCar.getColor())) {
}
else {
fail("Get the wrong car!");
}
}
Class: org.apache.cxf.systest.type_test.AbstractTypeTestClient APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testDateTime() throws Exception {
if (!shouldRunTest("DateTime")) {
return;
}
javax.xml.datatype.DatatypeFactory datatypeFactory=javax.xml.datatype.DatatypeFactory.newInstance();
XMLGregorianCalendar x=datatypeFactory.newXMLGregorianCalendar();
x.setYear(1975);
x.setMonth(5);
x.setDay(5);
x.setHour(12);
x.setMinute(30);
x.setSecond(15);
XMLGregorianCalendar yOrig=datatypeFactory.newXMLGregorianCalendar();
yOrig.setYear(2005);
yOrig.setMonth(4);
yOrig.setDay(1);
yOrig.setHour(17);
yOrig.setMinute(59);
yOrig.setSecond(30);
Holder y=new Holder(yOrig);
Holder z=new Holder();
XMLGregorianCalendar ret;
if (testDocLiteral) {
ret=docClient.testDateTime(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testDateTime(x,y,z);
}
else {
ret=rpcClient.testDateTime(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testDateTime(): Incorrect value for inout param",equalsDateTime(x,y.value));
assertTrue("testDateTime(): Incorrect value for out param",equalsDateTime(yOrig,z.value));
assertTrue("testDateTime(): Incorrect return value",equalsDateTime(x,ret));
}
}
BranchVerifier UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testSimpleRestriction4() throws Exception {
if (!shouldRunTest("SimpleRestriction4")) {
return;
}
String x="x";
String yOrig="y";
Holder y=new Holder(yOrig);
Holder z=new Holder();
String ret;
if (testDocLiteral) {
ret=docClient.testSimpleRestriction4(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testSimpleRestriction4(x,y,z);
}
else {
ret=rpcClient.testSimpleRestriction4(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testSimpleRestriction4(): Incorrect value for inout param",x,y.value);
assertEquals("testSimpleRestriction4(): Incorrect value for out param",yOrig,z.value);
assertEquals("testSimpleRestriction4(): Incorrect return value",x,ret);
}
if (testDocLiteral || testXMLBinding) {
x="str";
y=new Holder(yOrig);
z=new Holder();
try {
ret=testDocLiteral ? docClient.testSimpleRestriction4(x,y,z) : xmlClient.testSimpleRestriction4(x,y,z);
fail("x parameter minLength=5 restriction is violated.");
}
catch ( Exception ex) {
}
}
}
IterativeVerifier BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testInteger() throws Exception {
if (!shouldRunTest("Integer")) {
return;
}
BigInteger valueSets[][]={{new BigInteger("-1234567890"),new BigInteger("1234567890")},{new BigInteger("-" + String.valueOf(Long.MAX_VALUE * Long.MAX_VALUE)),new BigInteger(String.valueOf(Long.MAX_VALUE * Long.MAX_VALUE))}};
for (int i=0; i < valueSets.length; i++) {
BigInteger x=valueSets[i][0];
Holder yOrig=new Holder(valueSets[i][1]);
Holder y=new Holder(valueSets[i][1]);
Holder z=new Holder();
BigInteger ret;
if (testDocLiteral) {
ret=docClient.testInteger(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testInteger(x,y,z);
}
else {
ret=rpcClient.testInteger(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testInteger(): Incorrect value for inout param",x,y.value);
assertEquals("testInteger(): Incorrect value for out param",yOrig.value,z.value);
assertEquals("testInteger(): Incorrect return value",x,ret);
}
}
}
IterativeVerifier BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testQName() throws Exception {
if (!shouldRunTest("QName")) {
return;
}
String valueSets[][]={{"NoNamespaceService",""},{"HelloWorldService","http://www.iona.com/services"},{I18NStrings.JAP_SIMPLE_STRING,"http://www.iona.com/iona"},{"MyService","http://www.iona.com/iona"}};
for (int i=0; i < valueSets.length; i++) {
QName x=new QName(valueSets[i][1],valueSets[i][0]);
QName yOrig=new QName("http://www.iona.com/inoutqname","InOutQName");
Holder y=new Holder(yOrig);
Holder z=new Holder();
QName ret;
if (testDocLiteral) {
ret=docClient.testQName(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testQName(x,y,z);
}
else {
ret=rpcClient.testQName(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testQName(): Incorrect value for inout param",x,y.value);
assertEquals("testQName(): Incorrect value for out param",yOrig,z.value);
assertEquals("testQName(): Incorrect return value",x,ret);
}
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testGYearMonth() throws Exception {
if (!shouldRunTest("GYearMonth")) {
return;
}
javax.xml.datatype.DatatypeFactory datatypeFactory=javax.xml.datatype.DatatypeFactory.newInstance();
XMLGregorianCalendar x=datatypeFactory.newXMLGregorianCalendar("2004-08");
XMLGregorianCalendar yOrig=datatypeFactory.newXMLGregorianCalendar("2003-12+05:00");
Holder y=new Holder(yOrig);
Holder z=new Holder();
XMLGregorianCalendar ret;
if (testDocLiteral) {
ret=docClient.testGYearMonth(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testGYearMonth(x,y,z);
}
else {
ret=rpcClient.testGYearMonth(x,y,z);
}
assertTrue("testGYearMonth(): Incorrect value for inout param",x.equals(y.value));
assertTrue("testGYearMonth(): Incorrect value for out param",yOrig.equals(z.value));
assertTrue("testGYearMonth(): Incorrect return value",x.equals(ret));
}
IterativeVerifier BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testUnsignedByte() throws Exception {
if (!shouldRunTest("UnsignedByte")) {
return;
}
short valueSets[][]={{0,1},{1,0},{0,Byte.MAX_VALUE * 2 + 1}};
for (int i=0; i < valueSets.length; i++) {
short x=valueSets[i][0];
Holder yOrig=new Holder(valueSets[i][1]);
Holder y=new Holder(valueSets[i][1]);
Holder z=new Holder();
short ret;
if (testDocLiteral) {
ret=docClient.testUnsignedByte(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testUnsignedByte(x,y,z);
}
else {
ret=rpcClient.testUnsignedByte(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testUnsignedByte(): Incorrect value for inout param",Short.valueOf(x),y.value);
assertEquals("testUnsignedByte(): Incorrect value for out param",yOrig.value,z.value);
assertEquals("testUnsignedByte(): Incorrect return value",x,ret);
}
}
}
IterativeVerifier BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testPositiveInteger() throws Exception {
if (!shouldRunTest("PositiveInteger")) {
return;
}
BigInteger valueSets[][]={{new BigInteger("1"),new BigInteger("1234567890")},{new BigInteger(String.valueOf(Integer.MAX_VALUE * Integer.MAX_VALUE)),new BigInteger(String.valueOf(Long.MAX_VALUE * Long.MAX_VALUE))}};
for (int i=0; i < valueSets.length; i++) {
BigInteger x=valueSets[i][0];
Holder yOrig=new Holder(valueSets[i][1]);
Holder y=new Holder(valueSets[i][1]);
Holder z=new Holder();
BigInteger ret;
if (testDocLiteral) {
ret=docClient.testPositiveInteger(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testPositiveInteger(x,y,z);
}
else {
ret=rpcClient.testPositiveInteger(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testPositiveInteger(): Incorrect value for inout param",x,y.value);
assertEquals("testPositiveInteger(): Incorrect value for out param",yOrig.value,z.value);
assertEquals("testPositiveInteger(): Incorrect return value",x,ret);
}
}
}
BranchVerifier UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testSimpleRestriction5() throws Exception {
if (!shouldRunTest("SimpleRestriction5")) {
return;
}
String x="str_x";
String yOrig="string_yyy";
Holder y=new Holder(yOrig);
Holder z=new Holder();
String ret;
if (testDocLiteral) {
ret=docClient.testSimpleRestriction5(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testSimpleRestriction5(x,y,z);
}
else {
ret=rpcClient.testSimpleRestriction5(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testSimpleRestriction5(): Incorrect value for inout param",x,y.value);
assertEquals("testSimpleRestriction5(): Incorrect value for out param",yOrig,z.value);
assertEquals("testSimpleRestriction5(): Incorrect return value",x,ret);
}
if (testDocLiteral || testXMLBinding) {
x="str";
y=new Holder(yOrig);
z=new Holder();
try {
ret=docClient.testSimpleRestriction5(x,y,z);
fail("maxLength=10 && minLength=5 restriction is violated.");
}
catch ( Exception ex) {
}
x="string_x";
yOrig="string_yyyyyy";
y=new Holder(yOrig);
z=new Holder();
try {
ret=testDocLiteral ? docClient.testSimpleRestriction5(x,y,z) : xmlClient.testSimpleRestriction5(x,y,z);
fail("maxLength=10 && minLength=5 restriction is violated.");
}
catch ( Exception ex) {
}
}
}
BranchVerifier UtilityVerifier BooleanVerifier InternalCallVerifier HybridVerifier
@Test public void testBase64Binary() throws Exception {
if (!shouldRunTest("Base64Binary")) {
return;
}
byte[] x="hello".getBytes();
Holder y=new Holder("goodbye".getBytes());
Holder yOriginal=new Holder("goodbye".getBytes());
Holder z=new Holder();
byte[] ret;
if (testDocLiteral) {
ret=docClient.testBase64Binary(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testBase64Binary(x,y,z);
}
else {
ret=rpcClient.testBase64Binary(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testBase64Binary(): Incorrect value for inout param",Arrays.equals(x,y.value));
assertTrue("testBase64Binary(): Incorrect value for out param",Arrays.equals(yOriginal.value,z.value));
assertTrue("testBase64Binary(): Incorrect return value",Arrays.equals(x,ret));
}
try {
y=new Holder();
z=new Holder();
if (testDocLiteral) {
docClient.testBase64Binary(x,y,z);
}
else if (testXMLBinding) {
xmlClient.testBase64Binary(x,y,z);
}
else {
rpcClient.testBase64Binary(x,y,z);
}
fail("Uninitialized Holder for inout parameter should have thrown an error.");
}
catch ( Exception e) {
}
}
IterativeVerifier BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testColourEnum() throws Exception {
if (!shouldRunTest("ColourEnum")) {
return;
}
String[] xx={"RED","GREEN","BLUE"};
String[] yy={"GREEN","BLUE","RED"};
Holder z=new Holder();
for (int i=0; i < 3; i++) {
ColourEnum x=ColourEnum.fromValue(xx[i]);
ColourEnum yOrig=ColourEnum.fromValue(yy[i]);
Holder y=new Holder(yOrig);
ColourEnum ret;
if (testDocLiteral) {
ret=docClient.testColourEnum(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testColourEnum(x,y,z);
}
else {
ret=rpcClient.testColourEnum(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testColourEnum(): Incorrect value for inout param",x.value(),y.value.value());
assertEquals("testColourEnum(): Incorrect value for out param",yOrig.value(),z.value.value());
assertEquals("testColourEnum(): Incorrect return value",x.value(),ret.value());
}
}
}
BranchVerifier UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testSimpleRestriction2() throws Exception {
if (!shouldRunTest("SimpleRestriction2")) {
return;
}
String x="str_x";
String yOrig="string_yyy";
Holder y=new Holder(yOrig);
Holder z=new Holder();
String ret;
if (testDocLiteral) {
ret=docClient.testSimpleRestriction2(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testSimpleRestriction2(x,y,z);
}
else {
ret=rpcClient.testSimpleRestriction2(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testSimpleRestriction2(): Incorrect value for inout param",x,y.value);
assertEquals("testSimpleRestriction2(): Incorrect value for out param",yOrig,z.value);
assertEquals("testSimpleRestriction2(): Incorrect return value",x,ret);
}
if (testDocLiteral || testXMLBinding) {
x="str";
y=new Holder(yOrig);
z=new Holder();
try {
ret=testDocLiteral ? docClient.testSimpleRestriction2(x,y,z) : xmlClient.testSimpleRestriction2(x,y,z);
fail("minLength=5 restriction is violated.");
}
catch ( Exception ex) {
}
}
}
IterativeVerifier BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testUnsignedShort() throws Exception {
if (!shouldRunTest("UnsignedShort")) {
return;
}
int valueSets[][]={{0,1},{1,0},{0,Short.MAX_VALUE * 2 + 1}};
for (int i=0; i < valueSets.length; i++) {
int x=valueSets[i][0];
Holder yOrig=new Holder(valueSets[i][1]);
Holder y=new Holder(valueSets[i][1]);
Holder z=new Holder();
int ret;
if (testDocLiteral) {
ret=docClient.testUnsignedShort(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testUnsignedShort(x,y,z);
}
else {
ret=rpcClient.testUnsignedShort(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testUnsignedShort(): Incorrect value for inout param",Integer.valueOf(x),y.value);
assertEquals("testUnsignedShort(): Incorrect value for out param",yOrig.value,z.value);
assertEquals("testUnsignedShort(): Incorrect return value",x,ret);
}
}
}
IterativeVerifier BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testInt() throws Exception {
if (!shouldRunTest("Int")) {
return;
}
int valueSets[][]={{5,10},{-10,50},{Integer.MIN_VALUE,Integer.MAX_VALUE}};
for (int i=0; i < valueSets.length; i++) {
int x=valueSets[i][0];
Holder yOrig=new Holder(valueSets[i][1]);
Holder y=new Holder(valueSets[i][1]);
Holder z=new Holder();
int ret;
if (testDocLiteral) {
ret=docClient.testInt(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testInt(x,y,z);
}
else {
ret=rpcClient.testInt(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testInt(): Incorrect value for inout param",Integer.valueOf(x),y.value);
assertEquals("testInt(): Incorrect value for out param",yOrig.value,z.value);
assertEquals("testInt(): Incorrect return value",x,ret);
}
}
}
BranchVerifier UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testSimpleRestriction3() throws Exception {
if (!shouldRunTest("SimpleRestriction3")) {
return;
}
String x="str_x";
String yOrig="string_yyy";
Holder y=new Holder(yOrig);
Holder z=new Holder();
String ret;
if (testDocLiteral) {
ret=docClient.testSimpleRestriction3(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testSimpleRestriction3(x,y,z);
}
else {
ret=rpcClient.testSimpleRestriction3(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testSimpleRestriction3(): Incorrect value for inout param",x,y.value);
assertEquals("testSimpleRestriction3(): Incorrect value for out param",yOrig,z.value);
assertEquals("testSimpleRestriction3(): Incorrect return value",x,ret);
}
if (testDocLiteral || testXMLBinding) {
x="str";
y=new Holder(yOrig);
z=new Holder();
try {
ret=docClient.testSimpleRestriction3(x,y,z);
fail("x parameter maxLength=10 && minLength=5 restriction is violated.");
}
catch ( Exception ex) {
}
x="string_x";
yOrig="string_yyyyyy";
y=new Holder(yOrig);
z=new Holder();
try {
ret=testDocLiteral ? docClient.testSimpleRestriction3(x,y,z) : xmlClient.testSimpleRestriction3(x,y,z);
fail("y parameter maxLength=10 && minLength=5 restriction is violated.");
}
catch ( Exception ex) {
}
}
}
IterativeVerifier BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testUnsignedLong() throws Exception {
if (!shouldRunTest("UnsignedLong")) {
return;
}
BigInteger valueSets[][]={{new BigInteger("0"),new BigInteger("1")},{new BigInteger("1"),new BigInteger("0")},{new BigInteger("0"),new BigInteger(String.valueOf(Long.MAX_VALUE * Long.MAX_VALUE))}};
for (int i=0; i < valueSets.length; i++) {
BigInteger x=valueSets[i][0];
Holder yOrig=new Holder(valueSets[i][1]);
Holder y=new Holder(valueSets[i][1]);
Holder z=new Holder();
BigInteger ret;
if (testDocLiteral) {
ret=docClient.testUnsignedLong(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testUnsignedLong(x,y,z);
}
else {
ret=rpcClient.testUnsignedLong(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testUnsignedLong(): Incorrect value for inout param",x,y.value);
assertEquals("testUnsignedLong(): Incorrect value for out param",yOrig.value,z.value);
assertEquals("testUnsignedLong(): Incorrect return value",x,ret);
}
}
}
IterativeVerifier BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testNonNegativeInteger() throws Exception {
if (!shouldRunTest("NonNegativeInteger")) {
return;
}
BigInteger valueSets[][]={{new BigInteger("0"),new BigInteger("1234567890")},{new BigInteger(String.valueOf(Integer.MAX_VALUE * Integer.MAX_VALUE)),new BigInteger(String.valueOf(Long.MAX_VALUE * Long.MAX_VALUE))}};
for (int i=0; i < valueSets.length; i++) {
BigInteger x=valueSets[i][0];
Holder yOrig=new Holder(valueSets[i][1]);
Holder y=new Holder(valueSets[i][1]);
Holder z=new Holder();
BigInteger ret;
if (testDocLiteral) {
ret=docClient.testNonNegativeInteger(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testNonNegativeInteger(x,y,z);
}
else {
ret=rpcClient.testNonNegativeInteger(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testNonNegativeInteger(): Incorrect value for inout param",x,y.value);
assertEquals("testNonNegativeInteger(): Incorrect value for out param",yOrig.value,z.value);
assertEquals("testNonNegativeInteger(): Incorrect return value",x,ret);
}
}
}
IterativeVerifier BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testNegativeInteger() throws Exception {
if (!shouldRunTest("NegativeInteger")) {
return;
}
BigInteger valueSets[][]={{new BigInteger("-1"),new BigInteger("-1234567890")},{new BigInteger("-" + String.valueOf(Integer.MAX_VALUE * Integer.MAX_VALUE)),new BigInteger("-" + String.valueOf(Long.MAX_VALUE * Long.MAX_VALUE))}};
for (int i=0; i < valueSets.length; i++) {
BigInteger x=valueSets[i][0];
Holder yOrig=new Holder(valueSets[i][1]);
Holder y=new Holder(valueSets[i][1]);
Holder z=new Holder();
BigInteger ret;
if (testDocLiteral) {
ret=docClient.testNegativeInteger(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testNegativeInteger(x,y,z);
}
else {
ret=rpcClient.testNegativeInteger(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testNegativeInteger(): Incorrect value for inout param",x,y.value);
assertEquals("testNegativeInteger(): Incorrect value for out param",yOrig.value,z.value);
assertEquals("testNegativeInteger(): Incorrect return value",x,ret);
}
}
}
IterativeVerifier BranchVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testSimpleListRestriction2() throws Exception {
if (!shouldRunTest("SimpleListRestriction2")) {
return;
}
if (testDocLiteral || testXMLBinding) {
List x=Arrays.asList("I","am","SimpleList");
List yOrig=Arrays.asList("Does","SimpleList","Work");
Holder> y=new Holder>(yOrig);
Holder> z=new Holder>();
List ret=testDocLiteral ? docClient.testSimpleListRestriction2(x,y,z) : xmlClient.testSimpleListRestriction2(x,y,z);
if (!perfTestOnly) {
assertTrue("testStringList(): Incorrect value for inout param",x.equals(y.value));
assertTrue("testStringList(): Incorrect value for out param",yOrig.equals(z.value));
assertTrue("testStringList(): Incorrect return value",x.equals(ret));
}
x=new ArrayList();
y=new Holder>(yOrig);
z=new Holder>();
try {
ret=testDocLiteral ? docClient.testSimpleListRestriction2(x,y,z) : xmlClient.testSimpleListRestriction2(x,y,z);
fail("length=10 restriction is violated.");
}
catch ( Exception ex) {
}
}
else {
String[] x={"I","am","SimpleList"};
String[] yOrig={"Does","SimpleList","Work"};
Holder y=new Holder(yOrig);
Holder z=new Holder();
String[] ret=rpcClient.testSimpleListRestriction2(x,y,z);
assertTrue(y.value.length == 3);
assertTrue(z.value.length == 3);
assertTrue(ret.length == 3);
if (!perfTestOnly) {
for (int i=0; i < 3; i++) {
assertEquals("testStringList(): Incorrect value for inout param",x[i],y.value[i]);
assertEquals("testStringList(): Incorrect value for out param",yOrig[i],z.value[i]);
assertEquals("testStringList(): Incorrect return value",x[i],ret[i]);
}
}
}
}
BooleanVerifier InternalCallVerifier
@Test public void testToken() throws Exception {
if (!shouldRunTest("Token")) {
return;
}
String x="token";
String yOrig="another token";
Holder y=new Holder(yOrig);
Holder z=new Holder();
String ret;
if (testDocLiteral) {
ret=docClient.testToken(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testToken(x,y,z);
}
else {
ret=rpcClient.testToken(x,y,z);
}
assertTrue("testToken(): Incorrect value for inout param",x.equals(y.value));
assertTrue("testToken(): Incorrect value for out param",yOrig.equals(z.value));
assertTrue("testToken(): Incorrect return value",x.equals(ret));
}
IterativeVerifier BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testByte() throws Exception {
if (!shouldRunTest("Byte")) {
return;
}
byte valueSets[][]={{0,1},{-1,0},{Byte.MIN_VALUE,Byte.MAX_VALUE}};
for (int i=0; i < valueSets.length; i++) {
byte x=valueSets[i][0];
Holder yOrig=new Holder(valueSets[i][1]);
Holder y=new Holder(valueSets[i][1]);
Holder z=new Holder();
byte ret;
if (testDocLiteral) {
ret=docClient.testByte(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testByte(x,y,z);
}
else {
ret=rpcClient.testByte(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testByte(): Incorrect value for inout param",Byte.valueOf(x),y.value);
assertEquals("testByte(): Incorrect value for out param",yOrig.value,z.value);
assertEquals("testByte(): Incorrect return value",x,ret);
}
}
}
IterativeVerifier BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testStringEnum() throws Exception {
if (!shouldRunTest("StringEnum")) {
return;
}
String[] xx={"a b c","d e f","g h i"};
String[] yy={"g h i","a b c","d e f"};
Holder z=new Holder();
for (int i=0; i < 3; i++) {
StringEnum x=StringEnum.fromValue(xx[i]);
StringEnum yOrig=StringEnum.fromValue(yy[i]);
Holder y=new Holder(yOrig);
StringEnum ret;
if (testDocLiteral) {
ret=docClient.testStringEnum(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testStringEnum(x,y,z);
}
else {
ret=rpcClient.testStringEnum(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testStringEnum(): Incorrect value for inout param",x.value(),y.value.value());
assertEquals("testStringEnum(): Incorrect value for out param",yOrig.value(),z.value.value());
assertEquals("testStringEnum(): Incorrect return value",x.value(),ret.value());
}
}
}
IterativeVerifier BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testAnyURIEnum() throws Exception {
if (!shouldRunTest("AnyURIEnum")) {
return;
}
String[] xx={"http://www.iona.com","http://www.google.com"};
String[] yy={"http://www.google.com","http://www.iona.com"};
Holder z=new Holder();
for (int i=0; i < 2; i++) {
AnyURIEnum x=AnyURIEnum.fromValue(xx[i]);
AnyURIEnum yOrig=AnyURIEnum.fromValue(yy[i]);
Holder y=new Holder(yOrig);
AnyURIEnum ret;
if (testDocLiteral) {
ret=docClient.testAnyURIEnum(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testAnyURIEnum(x,y,z);
}
else {
ret=rpcClient.testAnyURIEnum(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testAnyURIEnum(): Incorrect value for inout param",x.value(),y.value.value());
assertEquals("testAnyURIEnum(): Incorrect value for out param",yOrig.value(),z.value.value());
assertEquals("testAnyURIEnum(): Incorrect return value",x.value(),ret.value());
}
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testGYear() throws Exception {
if (!shouldRunTest("GYear")) {
return;
}
javax.xml.datatype.DatatypeFactory datatypeFactory=javax.xml.datatype.DatatypeFactory.newInstance();
XMLGregorianCalendar x=datatypeFactory.newXMLGregorianCalendar("2004");
XMLGregorianCalendar yOrig=datatypeFactory.newXMLGregorianCalendar("2003+05:00");
Holder y=new Holder(yOrig);
Holder z=new Holder();
XMLGregorianCalendar ret;
if (testDocLiteral) {
ret=docClient.testGYear(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testGYear(x,y,z);
}
else {
ret=rpcClient.testGYear(x,y,z);
}
assertTrue("testGYear(): Incorrect value for inout param",x.equals(y.value));
assertTrue("testGYear(): Incorrect value for out param",yOrig.equals(z.value));
assertTrue("testGYear(): Incorrect return value",x.equals(ret));
}
APIUtilityVerifier BranchVerifier UtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testDate() throws Exception {
if (!shouldRunTest("Date")) {
return;
}
javax.xml.datatype.DatatypeFactory datatypeFactory=javax.xml.datatype.DatatypeFactory.newInstance();
XMLGregorianCalendar x=datatypeFactory.newXMLGregorianCalendar();
x.setYear(1975);
x.setMonth(5);
x.setDay(5);
XMLGregorianCalendar yOrig=datatypeFactory.newXMLGregorianCalendar();
yOrig.setYear(2004);
yOrig.setMonth(4);
yOrig.setDay(1);
Holder y=new Holder(yOrig);
Holder z=new Holder();
XMLGregorianCalendar ret;
if (testDocLiteral) {
ret=docClient.testDate(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testDate(x,y,z);
}
else {
ret=rpcClient.testDate(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testDate(): Incorrect value for inout param " + x + " != "+ y.value,equalsDate(x,y.value));
assertTrue("testDate(): Incorrect value for out param",equalsDate(yOrig,z.value));
assertTrue("testDate(): Incorrect return value",equalsDate(x,ret));
}
x=datatypeFactory.newXMLGregorianCalendar();
yOrig=datatypeFactory.newXMLGregorianCalendar();
y=new Holder(yOrig);
z=new Holder();
try {
if (testDocLiteral) {
ret=docClient.testDate(x,y,z);
}
else {
ret=rpcClient.testDate(x,y,z);
}
fail("Expected to catch WebServiceException when calling" + " testDate() with uninitialized parameters.");
}
catch ( RuntimeException re) {
assertNotNull(re);
}
}
BranchVerifier UtilityVerifier BooleanVerifier InternalCallVerifier HybridVerifier
@Test public void testBase64BinaryRestriction() throws Exception {
if (!shouldRunTest("Base64BinaryRestriction")) {
return;
}
byte[] x="string_xxx".getBytes();
byte[] yOrig="string_yyy".getBytes();
Holder y=new Holder(yOrig);
Holder z=new Holder();
byte[] ret;
if (testDocLiteral) {
ret=docClient.testBase64BinaryRestriction(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testBase64BinaryRestriction(x,y,z);
}
else {
ret=rpcClient.testBase64BinaryRestriction(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testBase64BinaryRestriction(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testBase64BinaryRestriction(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testBase64BinaryRestriction(): Incorrect return value",equals(x,ret));
}
if (testDocLiteral) {
x="string_xxxxx".getBytes();
y=new Holder(yOrig);
z=new Holder();
try {
ret=docClient.testBase64BinaryRestriction(x,y,z);
fail("length=10 restriction is violated.");
}
catch ( Exception ex) {
}
}
}
IterativeVerifier BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testAnyURI() throws Exception {
if (!shouldRunTest("AnyURI")) {
return;
}
String valueSets[][]={{"file:///root%20%20/-;?&+","file:///w:/test!artix~java*"},{"http://iona.com/","file:///z:/mail_iona=com,\'xmlbus\'"},{"mailto:windows@systems","file:///"}};
for (int i=0; i < valueSets.length; i++) {
String x=new String(valueSets[i][0]);
String yOrig=new String(valueSets[i][1]);
Holder y=new Holder(yOrig);
Holder z=new Holder();
String ret;
if (testDocLiteral) {
ret=docClient.testAnyURI(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testAnyURI(x,y,z);
}
else {
ret=rpcClient.testAnyURI(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testAnyURI(): Incorrect value for inout param",x,y.value);
assertEquals("testAnyURI(): Incorrect value for out param",yOrig,z.value);
assertEquals("testAnyURI(): Incorrect return value",x,ret);
}
}
}
BooleanVerifier InternalCallVerifier
@Test public void testNMTOKEN() throws Exception {
if (!shouldRunTest("NMTOKEN")) {
return;
}
String x="123:abc";
String yOrig="abc.-_:";
Holder y=new Holder(yOrig);
Holder z=new Holder();
String ret;
if (testDocLiteral) {
ret=docClient.testNMTOKEN(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testNMTOKEN(x,y,z);
}
else {
ret=rpcClient.testNMTOKEN(x,y,z);
}
assertTrue("testNMTOKEN(): Incorrect value for inout param",x.equals(y.value));
assertTrue("testNMTOKEN(): Incorrect value for out param",yOrig.equals(z.value));
assertTrue("testNMTOKEN(): Incorrect return value",x.equals(ret));
}
BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testNMTOKENS() throws Exception {
if (!shouldRunTest("NMTOKENS")) {
return;
}
if (testDocLiteral) {
List x=Arrays.asList("123:abc");
List yOrig=Arrays.asList("abc.-_:","a");
Holder> y=new Holder>(yOrig);
Holder> z=new Holder>();
List ret=docClient.testNMTOKENS(x,y,z);
assertTrue("testNMTOKENS(): Incorrect value for inout param",x.equals(y.value));
assertTrue("testNMTOKENS(): Incorrect value for out param",yOrig.equals(z.value));
assertTrue("testNMTOKENS(): Incorrect return value",x.equals(ret));
}
else if (testXMLBinding) {
List x=Arrays.asList("123:abc");
List yOrig=Arrays.asList("abc.-_:","a");
Holder> y=new Holder>(yOrig);
Holder> z=new Holder>();
List ret=xmlClient.testNMTOKENS(x,y,z);
assertTrue("testNMTOKENS(): Incorrect value for inout param",x.equals(y.value));
assertTrue("testNMTOKENS(): Incorrect value for out param",yOrig.equals(z.value));
assertTrue("testNMTOKENS(): Incorrect return value",x.equals(ret));
}
else {
String[] x=new String[1];
x[0]="123:abc";
String[] yOrig=new String[2];
yOrig[0]="abc.-_:";
yOrig[1]="a";
Holder y=new Holder(yOrig);
Holder z=new Holder();
String[] ret=rpcClient.testNMTOKENS(x,y,z);
assertTrue("testNMTOKENS(): Incorrect value for inout param",Arrays.equals(x,y.value));
assertTrue("testNMTOKENS(): Incorrect value for out param",Arrays.equals(yOrig,z.value));
assertTrue("testNMTOKENS(): Incorrect return value",Arrays.equals(x,ret));
}
}
IterativeVerifier BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testBoolean() throws Exception {
if (!shouldRunTest("Boolean")) {
return;
}
boolean valueSets[][]={{true,false},{true,true},{false,true},{false,false}};
for (int i=0; i < valueSets.length; i++) {
boolean x=valueSets[i][0];
Holder yOrig=new Holder(valueSets[i][1]);
Holder y=new Holder(valueSets[i][1]);
Holder z=new Holder();
boolean ret;
if (testDocLiteral) {
ret=docClient.testBoolean(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testBoolean(x,y,z);
}
else {
ret=rpcClient.testBoolean(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testBoolean(): Incorrect value for inout param",Boolean.valueOf(x),y.value);
assertEquals("testBoolean(): Incorrect value for out param",yOrig.value,z.value);
assertEquals("testBoolean(): Incorrect return value",x,ret);
}
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testTime() throws Exception {
if (!shouldRunTest("Time")) {
return;
}
javax.xml.datatype.DatatypeFactory datatypeFactory=javax.xml.datatype.DatatypeFactory.newInstance();
XMLGregorianCalendar x=datatypeFactory.newXMLGregorianCalendar();
x.setHour(12);
x.setMinute(14);
x.setSecond(5);
XMLGregorianCalendar yOrig=datatypeFactory.newXMLGregorianCalendar();
yOrig.setHour(22);
yOrig.setMinute(4);
yOrig.setSecond(15);
yOrig.setMillisecond(250);
Holder y=new Holder(yOrig);
Holder z=new Holder();
XMLGregorianCalendar ret;
if (testDocLiteral) {
ret=docClient.testTime(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testTime(x,y,z);
}
else {
ret=rpcClient.testTime(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testTime(): Incorrect value for inout param",equalsTime(x,y.value));
assertTrue("testTime(): Incorrect value for out param",equalsTime(yOrig,z.value));
assertTrue("testTime(): Incorrect return value",equalsTime(x,ret));
}
}
IterativeVerifier BranchVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testFloat() throws Exception {
if (!shouldRunTest("Float")) {
return;
}
float delta=0.0f;
float valueSets[][]=getTestFloatData();
for (int i=0; i < valueSets.length; i++) {
float x=valueSets[i][0];
Holder yOrig=new Holder(valueSets[i][1]);
Holder y=new Holder(valueSets[i][1]);
Holder z=new Holder();
float ret;
if (testDocLiteral) {
ret=docClient.testFloat(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testFloat(x,y,z);
}
else {
ret=rpcClient.testFloat(x,y,z);
}
if (!perfTestOnly) {
assertEquals(i + ": testFloat(): Wrong value for inout param",x,y.value,delta);
assertEquals(i + ": testFloat(): Wrong value for out param",yOrig.value,z.value,delta);
assertEquals(i + ": testFloat(): Wrong return value",x,ret,delta);
}
}
float x=Float.NaN;
Holder yOrig=new Holder(0.0f);
Holder y=new Holder(0.0f);
Holder z=new Holder();
float ret;
if (testDocLiteral) {
ret=docClient.testFloat(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testFloat(x,y,z);
}
else {
ret=rpcClient.testFloat(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testFloat(): Incorrect value for inout param",Float.isNaN(y.value));
assertEquals("testFloat(): Incorrect value for out param",yOrig.value,z.value,delta);
assertTrue("testFloat(): Incorrect return value",Float.isNaN(ret));
}
}
IterativeVerifier BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testShort() throws Exception {
if (!shouldRunTest("Short")) {
return;
}
short valueSets[][]={{0,1},{-1,0},{Short.MIN_VALUE,Short.MAX_VALUE}};
for (int i=0; i < valueSets.length; i++) {
short x=valueSets[i][0];
Holder yOrig=new Holder(valueSets[i][1]);
Holder y=new Holder(valueSets[i][1]);
Holder z=new Holder();
short ret;
if (testDocLiteral) {
ret=docClient.testShort(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testShort(x,y,z);
}
else {
ret=rpcClient.testShort(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testShort(): Incorrect value for inout param",Short.valueOf(x),y.value);
assertEquals("testShort(): Incorrect value for out param",yOrig.value,z.value);
assertEquals("testShort(): Incorrect return value",x,ret);
}
}
}
IterativeVerifier BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testDecimal() throws Exception {
if (!shouldRunTest("Decimal")) {
return;
}
BigDecimal valueSets[][]={{new BigDecimal("-1234567890.000000"),new BigDecimal("1234567890.000000")},{new BigDecimal("-" + String.valueOf(Long.MAX_VALUE * Long.MAX_VALUE) + ".000000"),new BigDecimal(String.valueOf(Long.MAX_VALUE * Long.MAX_VALUE) + ".000000")}};
for (int i=0; i < valueSets.length; i++) {
BigDecimal x=valueSets[i][0];
Holder yOrig=new Holder(valueSets[i][1]);
Holder y=new Holder(valueSets[i][1]);
Holder z=new Holder();
BigDecimal ret;
if (testDocLiteral) {
ret=docClient.testDecimal(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testDecimal(x,y,z);
}
else {
ret=rpcClient.testDecimal(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testDecimal(): Incorrect value for inout param",x,y.value);
assertEquals("testDecimal(): Incorrect value for out param",yOrig.value,z.value);
assertEquals("testDecimal(): Incorrect return value",x,ret);
}
}
}
IterativeVerifier BranchVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testNumberList() throws Exception {
if (!shouldRunTest("NumberList")) {
return;
}
if (testDocLiteral || testXMLBinding) {
List x=Arrays.asList(1,2,3);
List yOrig=Arrays.asList(10,100,1000);
Holder> y=new Holder>(yOrig);
Holder> z=new Holder>();
List ret=testDocLiteral ? docClient.testNumberList(x,y,z) : xmlClient.testNumberList(x,y,z);
if (!perfTestOnly) {
assertTrue("testNumberList(): Incorrect value for inout param",x.equals(y.value));
assertTrue("testNumberList(): Incorrect value for out param",yOrig.equals(z.value));
assertTrue("testNumberList(): Incorrect return value",x.equals(ret));
}
}
else {
Integer[] x={1,2,3};
Integer[] yOrig={10,100,1000};
Holder y=new Holder(yOrig);
Holder z=new Holder();
Integer[] ret=rpcClient.testNumberList(x,y,z);
assertTrue(y.value.length == 3);
assertTrue(z.value.length == 3);
assertTrue(ret.length == 3);
if (!perfTestOnly) {
for (int i=0; i < 3; i++) {
assertEquals("testNumberList(): Incorrect value for inout param",x[i],y.value[i]);
assertEquals("testNumberList(): Incorrect value for out param",yOrig[i],z.value[i]);
assertEquals("testNumberList(): Incorrect return value",x[i],ret[i]);
}
}
}
}
IterativeVerifier BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testStringI18N() throws Exception {
if (!shouldRunTest("StringI18N")) {
return;
}
String valueSets[][]={{"hello",I18NStrings.CHINESE_COMPLEX_STRING},{"hello",I18NStrings.JAP_SIMPLE_STRING}};
for (int i=0; i < valueSets.length; i++) {
String x=valueSets[i][0];
Holder yOrig=new Holder(valueSets[i][1]);
Holder y=new Holder(valueSets[i][1]);
Holder z=new Holder();
String ret;
if (testDocLiteral) {
ret=docClient.testString(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testString(x,y,z);
}
else {
ret=rpcClient.testString(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testStringI18N(): Incorrect value for inout param",x,y.value);
assertEquals("testStringI18N(): Incorrect value for out param",yOrig.value,z.value);
assertEquals("testStringI18N(): Incorrect return value",x,ret);
}
}
}
IterativeVerifier BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testDecimalEnum() throws Exception {
if (!shouldRunTest("DecimalEnum")) {
return;
}
BigDecimal[] xx={new BigDecimal("-10.34"),new BigDecimal("11.22"),new BigDecimal("14.55")};
BigDecimal[] yy={new BigDecimal("14.55"),new BigDecimal("-10.34"),new BigDecimal("11.22")};
Holder z=new Holder();
for (int i=0; i < 3; i++) {
DecimalEnum x=DecimalEnum.fromValue(xx[i]);
DecimalEnum yOrig=DecimalEnum.fromValue(yy[i]);
Holder y=new Holder(yOrig);
DecimalEnum ret;
if (testDocLiteral) {
ret=docClient.testDecimalEnum(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testDecimalEnum(x,y,z);
}
else {
ret=rpcClient.testDecimalEnum(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testDecimalEnum(): Incorrect value for inout param",x.value(),y.value.value());
assertEquals("testDecimalEnum(): Incorrect value for out param",yOrig.value(),z.value.value());
assertEquals("testDecimalEnum(): Incorrect return value",x.value(),ret.value());
}
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testDuration() throws Exception {
if (!shouldRunTest("Duration")) {
return;
}
javax.xml.datatype.DatatypeFactory datatypeFactory=javax.xml.datatype.DatatypeFactory.newInstance();
Duration x=datatypeFactory.newDuration("P1Y35DT60M60.500S");
Duration yOrig=datatypeFactory.newDuration("-P2MT24H60S");
Holder y=new Holder(yOrig);
Holder z=new Holder();
Duration ret;
if (testDocLiteral) {
ret=docClient.testDuration(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testDuration(x,y,z);
}
else {
ret=rpcClient.testDuration(x,y,z);
}
assertTrue("testDuration(): Incorrect value for inout param",x.equals(y.value));
assertTrue("testDuration(): Incorrect value for out param",yOrig.equals(z.value));
assertTrue("testDuration(): Incorrect return value",x.equals(ret));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testGMonthDay() throws Exception {
if (!shouldRunTest("GMonthDay")) {
return;
}
javax.xml.datatype.DatatypeFactory datatypeFactory=javax.xml.datatype.DatatypeFactory.newInstance();
XMLGregorianCalendar x=datatypeFactory.newXMLGregorianCalendar("--08-21");
XMLGregorianCalendar yOrig=datatypeFactory.newXMLGregorianCalendar("--12-05+05:00");
Holder y=new Holder(yOrig);
Holder z=new Holder();
XMLGregorianCalendar ret;
if (testDocLiteral) {
ret=docClient.testGMonthDay(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testGMonthDay(x,y,z);
}
else {
ret=rpcClient.testGMonthDay(x,y,z);
}
assertTrue("testGMonthDay(): Incorrect value for inout param",x.equals(y.value));
assertTrue("testGMonthDay(): Incorrect value for out param",yOrig.equals(z.value));
assertTrue("testGMonthDay(): Incorrect return value",x.equals(ret));
}
IterativeVerifier BranchVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testStringList() throws Exception {
if (!shouldRunTest("StringList")) {
return;
}
if (testDocLiteral || testXMLBinding) {
List x=Arrays.asList("I","am","SimpleList");
List yOrig=Arrays.asList("Does","SimpleList","Work");
Holder> y=new Holder>(yOrig);
Holder> z=new Holder>();
List ret=testDocLiteral ? docClient.testStringList(x,y,z) : xmlClient.testStringList(x,y,z);
if (!perfTestOnly) {
assertTrue("testStringList(): Incorrect value for inout param",x.equals(y.value));
assertTrue("testStringList(): Incorrect value for out param",yOrig.equals(z.value));
assertTrue("testStringList(): Incorrect return value",x.equals(ret));
}
if (testDocLiteral) {
try {
ret=docClient.testStringList(null,y,z);
}
catch ( SOAPFaultException ex) {
assertTrue(ex.getMessage(),ex.getMessage().contains("Unmarshalling"));
}
}
}
else {
String[] x={"I","am","SimpleList"};
String[] yOrig={"Does","SimpleList","Work"};
Holder y=new Holder(yOrig);
Holder z=new Holder();
String[] ret=rpcClient.testStringList(x,y,z);
assertTrue(y.value.length == 3);
assertTrue(z.value.length == 3);
assertTrue(ret.length == 3);
if (!perfTestOnly) {
for (int i=0; i < 3; i++) {
assertEquals("testStringList(): Incorrect value for inout param",x[i],y.value[i]);
assertEquals("testStringList(): Incorrect value for out param",yOrig[i],z.value[i]);
assertEquals("testStringList(): Incorrect return value",x[i],ret[i]);
}
}
}
}
IterativeVerifier BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testLong() throws Exception {
if (!shouldRunTest("Long")) {
return;
}
long valueSets[][]={{0,1},{-1,0},{Long.MIN_VALUE,Long.MAX_VALUE}};
for (int i=0; i < valueSets.length; i++) {
long x=valueSets[i][0];
Holder yOrig=new Holder(valueSets[i][1]);
Holder y=new Holder(valueSets[i][1]);
Holder z=new Holder();
long ret;
if (testDocLiteral) {
ret=docClient.testLong(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testLong(x,y,z);
}
else {
ret=rpcClient.testLong(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testLong(): Incorrect value for inout param",Long.valueOf(x),y.value);
assertEquals("testLong(): Incorrect value for out param",yOrig.value,z.value);
assertEquals("testLong(): Incorrect return value",x,ret);
}
}
}
IterativeVerifier BranchVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testSimpleUnionList() throws Exception {
if (!shouldRunTest("SimpleUnionList")) {
return;
}
if (testDocLiteral || testXMLBinding) {
List x=Arrays.asList("5","-7");
List yOrig=Arrays.asList("-9","7");
Holder> y=new Holder>(yOrig);
Holder> z=new Holder>();
List ret=testDocLiteral ? docClient.testSimpleUnionList(x,y,z) : xmlClient.testSimpleUnionList(x,y,z);
if (!perfTestOnly) {
assertTrue("testSimpleUnionList(): Incorrect value for inout param",x.equals(y.value));
assertTrue("testSimpleUnionList(): Incorrect value for out param",yOrig.equals(z.value));
assertTrue("testSimpleUnionList(): Incorrect return value",x.equals(ret));
}
}
else {
String[] x={"5","-7"};
String[] yOrig={"-9","7"};
Holder y=new Holder(yOrig);
Holder z=new Holder();
String[] ret=rpcClient.testSimpleUnionList(x,y,z);
assertTrue(y.value.length == 2);
assertTrue(z.value.length == 2);
assertTrue(ret.length == 2);
if (!perfTestOnly) {
for (int i=0; i < 2; i++) {
assertEquals("testSimpleUnionList(): Incorrect value for inout param",x[i],y.value[i]);
assertEquals("testSimpleUnionList(): Incorrect value for out param",yOrig[i],z.value[i]);
assertEquals("testSimpleUnionList(): Incorrect return value",x[i],ret[i]);
}
}
}
}
BooleanVerifier InternalCallVerifier
@Test public void testNCName() throws Exception {
if (!shouldRunTest("NCName")) {
return;
}
String x="abc-123";
String yOrig="abc.-";
Holder y=new Holder(yOrig);
Holder z=new Holder();
String ret;
if (testDocLiteral) {
ret=docClient.testNCName(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testNCName(x,y,z);
}
else {
ret=rpcClient.testNCName(x,y,z);
}
assertTrue("testNCName(): Incorrect value for inout param",x.equals(y.value));
assertTrue("testNCName(): Incorrect value for out param",yOrig.equals(z.value));
assertTrue("testNCName(): Incorrect return value",x.equals(ret));
}
IterativeVerifier BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testNonPositiveInteger() throws Exception {
if (!shouldRunTest("NonPositiveInteger")) {
return;
}
BigInteger valueSets[][]={{new BigInteger("0"),new BigInteger("-1234567890")},{new BigInteger("-" + String.valueOf(Integer.MAX_VALUE * Integer.MAX_VALUE)),new BigInteger("-" + String.valueOf(Long.MAX_VALUE * Long.MAX_VALUE))}};
for (int i=0; i < valueSets.length; i++) {
BigInteger x=valueSets[i][0];
Holder yOrig=new Holder(valueSets[i][1]);
Holder y=new Holder(valueSets[i][1]);
Holder z=new Holder();
BigInteger ret;
if (testDocLiteral) {
ret=docClient.testNonPositiveInteger(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testNonPositiveInteger(x,y,z);
}
else {
ret=rpcClient.testNonPositiveInteger(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testNonPositiveInteger(): Incorrect value for inout param",x,y.value);
assertEquals("testNonPositiveInteger(): Incorrect value for out param",yOrig.value,z.value);
assertEquals("testNonPositiveInteger(): Incorrect return value",x,ret);
}
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testGMonth() throws Exception {
if (!shouldRunTest("GMonth")) {
return;
}
javax.xml.datatype.DatatypeFactory datatypeFactory=javax.xml.datatype.DatatypeFactory.newInstance();
XMLGregorianCalendar x;
XMLGregorianCalendar yOrig;
try {
x=datatypeFactory.newXMLGregorianCalendar("--08");
yOrig=datatypeFactory.newXMLGregorianCalendar("--12+05:00");
}
catch ( java.lang.IllegalArgumentException iae) {
x=datatypeFactory.newXMLGregorianCalendar("--08--");
yOrig=datatypeFactory.newXMLGregorianCalendar("--12--+05:00");
}
Holder y=new Holder(yOrig);
Holder z=new Holder();
XMLGregorianCalendar ret;
if (testDocLiteral) {
ret=docClient.testGMonth(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testGMonth(x,y,z);
}
else {
ret=rpcClient.testGMonth(x,y,z);
}
assertTrue("testGMonth(): Incorrect value for inout param",x.equals(y.value));
assertTrue("testGMonth(): Incorrect value for out param",yOrig.equals(z.value));
assertTrue("testGMonth(): Incorrect return value",x.equals(ret));
}
BranchVerifier UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testSimpleRestriction() throws Exception {
if (!shouldRunTest("SimpleRestriction")) {
return;
}
String x="string_x";
String yOrig="string_y";
Holder y=new Holder(yOrig);
Holder z=new Holder();
String ret;
if (testDocLiteral) {
ret=docClient.testSimpleRestriction(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testSimpleRestriction(x,y,z);
}
else {
ret=rpcClient.testSimpleRestriction(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testSimpleRestriction(): Incorrect value for inout param",x,y.value);
assertEquals("testSimpleRestriction(): Incorrect value for out param",yOrig,z.value);
assertEquals("testSimpleRestriction(): Incorrect return value",x,ret);
}
if (testDocLiteral || testXMLBinding) {
x="string_xxxxx";
y=new Holder(yOrig);
z=new Holder();
try {
ret=docClient.testSimpleRestriction(x,y,z);
fail("x parameter maxLength=10 restriction is violated.");
}
catch ( Exception ex) {
}
x="string_x";
yOrig="string_yyyyyy";
y=new Holder(yOrig);
z=new Holder();
try {
ret=testDocLiteral ? docClient.testSimpleRestriction(x,y,z) : xmlClient.testSimpleRestriction(x,y,z);
fail("y parameter maxLength=10 restriction is violated.");
}
catch ( Exception ex) {
}
}
}
BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testHexBinary() throws Exception {
if (!shouldRunTest("HexBinary")) {
return;
}
byte[] x="hello".getBytes();
Holder y=new Holder("goodbye".getBytes());
Holder yOriginal=new Holder("goodbye".getBytes());
Holder z=new Holder();
byte[] ret;
if (testDocLiteral) {
ret=docClient.testHexBinary(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testHexBinary(x,y,z);
}
else {
ret=rpcClient.testHexBinary(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testHexBinary(): Incorrect value for inout param",Arrays.equals(x,y.value));
assertTrue("testHexBinary(): Incorrect value for out param",Arrays.equals(yOriginal.value,z.value));
assertTrue("testHexBinary(): Incorrect return value",Arrays.equals(x,ret));
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testGDay() throws Exception {
if (!shouldRunTest("GDay")) {
return;
}
javax.xml.datatype.DatatypeFactory datatypeFactory=javax.xml.datatype.DatatypeFactory.newInstance();
XMLGregorianCalendar x=datatypeFactory.newXMLGregorianCalendar("---21");
XMLGregorianCalendar yOrig=datatypeFactory.newXMLGregorianCalendar("---05+05:00");
Holder y=new Holder(yOrig);
Holder z=new Holder();
XMLGregorianCalendar ret;
if (testDocLiteral) {
ret=docClient.testGDay(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testGDay(x,y,z);
}
else {
ret=rpcClient.testGDay(x,y,z);
}
assertTrue("testGDay(): Incorrect value for inout param",x.equals(y.value));
assertTrue("testGDay(): Incorrect value for out param",yOrig.equals(z.value));
assertTrue("testGDay(): Incorrect return value",x.equals(ret));
}
IterativeVerifier BranchVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testDouble() throws Exception {
if (!shouldRunTest("Double")) {
return;
}
double delta=0.0d;
double valueSets[][]=getTestDoubleData();
for (int i=0; i < valueSets.length; i++) {
double x=valueSets[i][0];
Holder yOrig=new Holder(valueSets[i][1]);
Holder y=new Holder(valueSets[i][1]);
Holder z=new Holder();
double ret;
if (testDocLiteral) {
ret=docClient.testDouble(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testDouble(x,y,z);
}
else {
ret=rpcClient.testDouble(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testDouble(): Incorrect value for inout param",x,y.value,delta);
assertEquals("testDouble(): Incorrect value for out param",yOrig.value,z.value,delta);
assertEquals("testDouble(): Incorrect return value",x,ret,delta);
}
}
double x=Double.NaN;
Holder yOrig=new Holder(0.0);
Holder y=new Holder(0.0);
Holder z=new Holder();
double ret;
if (testDocLiteral) {
ret=docClient.testDouble(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testDouble(x,y,z);
}
else {
ret=rpcClient.testDouble(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testDouble(): Incorrect value for inout param",Double.isNaN(y.value));
assertEquals("testDouble(): Incorrect value for out param",yOrig.value,z.value,delta);
assertTrue("testDouble(): Incorrect return value",Double.isNaN(ret));
}
}
BooleanVerifier InternalCallVerifier
@Test public void testLanguage() throws Exception {
if (!shouldRunTest("Language")) {
return;
}
String x="abc";
String yOrig="abc-def";
Holder y=new Holder(yOrig);
Holder z=new Holder();
String ret;
if (testDocLiteral) {
ret=docClient.testLanguage(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testLanguage(x,y,z);
}
else {
ret=rpcClient.testLanguage(x,y,z);
}
assertTrue("testLanguage(): Incorrect value for inout param",x.equals(y.value));
assertTrue("testLanguage(): Incorrect value for out param",yOrig.equals(z.value));
assertTrue("testLanguage(): Incorrect return value",x.equals(ret));
}
BranchVerifier UtilityVerifier BooleanVerifier InternalCallVerifier HybridVerifier
@Test public void testHexBinaryRestriction() throws Exception {
if (!shouldRunTest("HexBinaryRestriction")) {
return;
}
byte[] x="x".getBytes();
byte[] yOrig="string_yyy".getBytes();
Holder y=new Holder(yOrig);
Holder z=new Holder();
byte[] ret;
if (testDocLiteral) {
ret=docClient.testHexBinaryRestriction(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testHexBinaryRestriction(x,y,z);
}
else {
ret=rpcClient.testHexBinaryRestriction(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testHexBinaryRestriction(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testHexBinaryRestriction(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testHexBinaryRestriction(): Incorrect return value",equals(x,ret));
}
if (testDocLiteral || testXMLBinding) {
x="".getBytes();
y=new Holder(yOrig);
z=new Holder();
try {
ret=docClient.testHexBinaryRestriction(x,y,z);
fail("maxLength=10 && minLength=1 restriction is violated.");
}
catch ( Exception ex) {
}
x="string_x".getBytes();
yOrig="string_yyyyyy".getBytes();
y=new Holder(yOrig);
z=new Holder();
try {
ret=testDocLiteral ? docClient.testHexBinaryRestriction(x,y,z) : xmlClient.testHexBinaryRestriction(x,y,z);
fail("maxLength=10 && minLength=1 restriction is violated.");
}
catch ( Exception ex) {
}
}
}
APIUtilityVerifier IterativeVerifier BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testString() throws Exception {
if (!shouldRunTest("String")) {
return;
}
int bufferSize=1000;
StringBuilder buffer=new StringBuilder(bufferSize);
StringBuilder buffer2=new StringBuilder(bufferSize);
for (int x=0; x < bufferSize; x++) {
buffer.append((char)('a' + (x % 26)));
buffer2.append((char)('A' + (x % 26)));
}
String valueSets[][]={{"hello","world"},{"is pi > 3 ?"," is pi < 4\\\""},{" ",""},{buffer.toString(),buffer2.toString()},{"jon&marry","marry&john"}};
for (int i=0; i < valueSets.length; i++) {
String x=valueSets[i][0];
Holder yOrig=new Holder(valueSets[i][1]);
Holder y=new Holder(valueSets[i][1]);
Holder z=new Holder();
String ret;
if (testDocLiteral) {
ret=docClient.testString(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testString(x,y,z);
}
else {
ret=rpcClient.testString(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testString(): Incorrect value for inout param",x,y.value);
assertEquals("testString(): Incorrect value for out param",yOrig.value,z.value);
assertEquals("testString(): Incorrect return value",x,ret);
}
}
}
IterativeVerifier BranchVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testQNameList() throws Exception {
if (!shouldRunTest("QNameList")) {
return;
}
if (testDocLiteral || testXMLBinding) {
List x=Arrays.asList(new QName("http://schemas.iona.com/type_test","testqname1"),new QName("http://schemas.iona.com/type_test","testqname2"),new QName("http://schemas.iona.com/type_test","testqname3"));
List yOrig=Arrays.asList(new QName("http://schemas.iona.com/type_test","testqname4"),new QName("http://schemas.iona.com/type_test","testqname5"),new QName("http://schemas.iona.com/type_test","testqname6"));
Holder> y=new Holder>(yOrig);
Holder> z=new Holder>();
List ret=testDocLiteral ? docClient.testQNameList(x,y,z) : xmlClient.testQNameList(x,y,z);
if (!perfTestOnly) {
assertTrue("testQNameList(): Incorrect value for inout param",x.equals(y.value));
assertTrue("testQNameList(): Incorrect value for out param",yOrig.equals(z.value));
assertTrue("testQNameList(): Incorrect return value",x.equals(ret));
}
}
else {
QName[] x={new QName("http://schemas.iona.com/type_test","testqname1"),new QName("http://schemas.iona.com/type_test","testqname2"),new QName("http://schemas.iona.com/type_test","testqname3")};
QName[] yOrig={new QName("http://schemas.iona.com/type_test","testqname4"),new QName("http://schemas.iona.com/type_test","testqname5"),new QName("http://schemas.iona.com/type_test","testqname6")};
Holder y=new Holder(yOrig);
Holder z=new Holder();
QName[] ret=rpcClient.testQNameList(x,y,z);
assertTrue(y.value.length == 3);
assertTrue(z.value.length == 3);
assertTrue(ret.length == 3);
if (!perfTestOnly) {
for (int i=0; i < 3; i++) {
assertEquals("testQNameList(): Incorrect value for inout param",x[i],y.value[i]);
assertEquals("testQNameList(): Incorrect value for out param",yOrig[i],z.value[i]);
assertEquals("testQNameList(): Incorrect return value",x[i],ret[i]);
}
}
}
}
BranchVerifier UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testSimpleRestriction6() throws Exception {
if (!shouldRunTest("SimpleRestriction6")) {
return;
}
String x="str_x";
String yOrig="y";
Holder y=new Holder(yOrig);
Holder z=new Holder();
String ret;
if (testDocLiteral) {
ret=docClient.testSimpleRestriction6(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testSimpleRestriction6(x,y,z);
}
else {
ret=rpcClient.testSimpleRestriction6(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testSimpleRestriction6(): Incorrect value for inout param",x,y.value);
assertEquals("testSimpleRestriction6(): Incorrect value for out param",yOrig,z.value);
assertEquals("testSimpleRestriction6(): Incorrect return value",x,ret);
}
if (testDocLiteral || testXMLBinding) {
x="string_x";
yOrig="string_y";
y=new Holder(yOrig);
z=new Holder();
try {
ret=testDocLiteral ? docClient.testSimpleRestriction6(x,y,z) : xmlClient.testSimpleRestriction6(x,y,z);
fail("maxLength=10 && minLength=5 restriction is violated.");
}
catch ( Exception ex) {
}
}
}
IterativeVerifier BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testUnsignedInt() throws Exception {
if (!shouldRunTest("UnsignedInt")) {
return;
}
long valueSets[][]={{0,((long)Integer.MAX_VALUE) * 2 + 1},{11,20},{1,0}};
for (int i=0; i < valueSets.length; i++) {
long x=valueSets[i][0];
long yOrig=valueSets[i][1];
Holder y=new Holder(valueSets[i][1]);
Holder z=new Holder();
long ret;
if (testDocLiteral) {
ret=docClient.testUnsignedInt(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testUnsignedInt(x,y,z);
}
else {
ret=rpcClient.testUnsignedInt(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testUnsignedInt(): Incorrect value for inout param",Long.valueOf(x),y.value);
assertEquals("testUnsignedInt(): Incorrect value for out param",Long.valueOf(yOrig),z.value);
assertEquals("testUnsignedInt(): Incorrect return value",x,ret);
}
}
}
IterativeVerifier BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testNMTokenEnum() throws Exception {
if (!shouldRunTest("NMTokenEnum")) {
return;
}
String[] xx={"hello","there"};
String[] yy={"there","hello"};
Holder z=new Holder();
for (int i=0; i < 2; i++) {
NMTokenEnum x=NMTokenEnum.fromValue(xx[i]);
NMTokenEnum yOrig=NMTokenEnum.fromValue(yy[i]);
Holder y=new Holder(yOrig);
NMTokenEnum ret;
if (testDocLiteral) {
ret=docClient.testNMTokenEnum(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testNMTokenEnum(x,y,z);
}
else {
ret=rpcClient.testNMTokenEnum(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testNMTokenEnum(): Incorrect value for inout param",x.value(),y.value.value());
assertEquals("testNMTokenEnum(): Incorrect value for out param",yOrig.value(),z.value.value());
assertEquals("testNMTokenEnum(): Incorrect return value",x.value(),ret.value());
}
}
}
BooleanVerifier InternalCallVerifier
@Test public void testNormalizedString() throws Exception {
if (!shouldRunTest("NormalizedString")) {
return;
}
String x=" normalized string ";
String yOrig=" another normalized string ";
Holder y=new Holder(yOrig);
Holder z=new Holder();
String ret;
if (testDocLiteral) {
ret=docClient.testNormalizedString(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testNormalizedString(x,y,z);
}
else {
ret=rpcClient.testNormalizedString(x,y,z);
}
assertTrue("testNormalizedString(): Incorrect value for inout param",x.equals(y.value));
assertTrue("testNormalizedString(): Incorrect value for out param",yOrig.equals(z.value));
assertTrue("testNormalizedString(): Incorrect return value",x.equals(ret));
}
BooleanVerifier InternalCallVerifier
@Test public void testName() throws Exception {
if (!shouldRunTest("Name")) {
return;
}
String x="abc:123";
String yOrig="abc.-_";
Holder y=new Holder(yOrig);
Holder z=new Holder();
String ret;
if (testDocLiteral) {
ret=docClient.testName(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testName(x,y,z);
}
else {
ret=rpcClient.testName(x,y,z);
}
assertTrue("testName(): Incorrect value for inout param",x.equals(y.value));
assertTrue("testName(): Incorrect value for out param",yOrig.equals(z.value));
assertTrue("testName(): Incorrect return value",x.equals(ret));
}
IterativeVerifier BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testNumberEnum() throws Exception {
if (!shouldRunTest("NumberEnum")) {
return;
}
int[] xx={1,2,3};
int[] yy={3,1,2};
Holder z=new Holder();
for (int i=0; i < 3; i++) {
NumberEnum x=NumberEnum.fromValue(xx[i]);
NumberEnum yOrig=NumberEnum.fromValue(yy[i]);
Holder y=new Holder(yOrig);
NumberEnum ret;
if (testDocLiteral) {
ret=docClient.testNumberEnum(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testNumberEnum(x,y,z);
}
else {
ret=rpcClient.testNumberEnum(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testNumberEnum(): Incorrect value for inout param",x.value(),y.value.value());
assertEquals("testNumberEnum(): Incorrect value for out param",yOrig.value(),z.value.value());
assertEquals("testNumberEnum(): Incorrect return value",x.value(),ret.value());
}
}
}
Class: org.apache.cxf.systest.type_test.AbstractTypeTestClient2 APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testChoiceWithSubstitutionGroupAbstract() throws Exception {
if (!shouldRunTest("ChoiceWithSubstitutionGroupAbstract")) {
return;
}
SgDerivedTypeB derivedB=new SgDerivedTypeB();
derivedB.setVarInt(new BigInteger("32"));
derivedB.setVarString("foo");
SgDerivedTypeC derivedC=new SgDerivedTypeC();
derivedC.setVarInt(new BigInteger("32"));
derivedC.setVarFloat(3.14f);
ObjectFactory objectFactory=new ObjectFactory();
JAXBElement extends SgBaseTypeA> elementB=objectFactory.createSg03DerivedElementB(derivedB);
JAXBElement extends SgBaseTypeA> elementC=objectFactory.createSg03DerivedElementC(derivedC);
ChoiceWithSubstitutionGroupAbstract x=new ChoiceWithSubstitutionGroupAbstract();
x.setSg03AbstractBaseElementA(elementC);
ChoiceWithSubstitutionGroupAbstract yOrig=new ChoiceWithSubstitutionGroupAbstract();
yOrig.setSg03AbstractBaseElementA(elementB);
Holder y=new Holder(yOrig);
Holder z=new Holder();
ChoiceWithSubstitutionGroupAbstract ret;
if (testDocLiteral) {
ret=docClient.testChoiceWithSubstitutionGroupAbstract(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testChoiceWithSubstitutionGroupAbstract(x,y,z);
}
else {
ret=rpcClient.testChoiceWithSubstitutionGroupAbstract(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testChoiceWithSubstitutionGroupAbstract(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testChoiceWithSubstitutionGroupAbstract(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testChoiceWithSubstitutionGroupAbstract(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testRecursiveUnionData() throws Exception {
if (!shouldRunTest("RecursiveUnionData")) {
return;
}
RecursiveUnion tmp1=new RecursiveUnion();
tmp1.setVarString("RecusiveUnion-1");
RecursiveUnion tmp2=new RecursiveUnion();
tmp2.setVarString("RecusiveUnion-2");
RecursiveUnionData x=new RecursiveUnionData();
ChoiceArray xChoice=new ChoiceArray();
xChoice.getItem().add(tmp1);
xChoice.getItem().add(tmp2);
x.setVarInt(5);
x.setVarChoiceArray(xChoice);
RecursiveUnionData yOrig=new RecursiveUnionData();
ChoiceArray yOrigchoice=new ChoiceArray();
xChoice.getItem().add(tmp1);
xChoice.getItem().add(tmp2);
yOrig.setVarInt(-5);
yOrig.setVarChoiceArray(yOrigchoice);
Holder y=new Holder(yOrig);
Holder z=new Holder();
RecursiveUnionData ret;
if (testDocLiteral) {
ret=docClient.testRecursiveUnionData(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testRecursiveUnionData(x,y,z);
}
else {
ret=rpcClient.testRecursiveUnionData(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testRecursiveUnionData(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testRecursiveUnionData(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testRecursiveUnionData(): Incorrect return value",equals(ret,x));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testSimpleAll() throws Exception {
if (!shouldRunTest("SimpleAll")) {
return;
}
SimpleAll x=new SimpleAll();
x.setVarFloat(3.14f);
x.setVarInt(42);
x.setVarString("Hello There");
x.setVarAttrString("Attr-x");
SimpleAll yOrig=new SimpleAll();
yOrig.setVarFloat(-9.14f);
yOrig.setVarInt(10);
yOrig.setVarString("Cheerio");
yOrig.setVarAttrString("Attr-y");
Holder y=new Holder(yOrig);
Holder z=new Holder();
SimpleAll ret;
if (testDocLiteral) {
ret=docClient.testSimpleAll(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testSimpleAll(x,y,z);
}
else {
ret=rpcClient.testSimpleAll(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testSimpleAll(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testSimpleAll(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testSimpleAll(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testStructWithList() throws Exception {
if (!shouldRunTest("StructWithList")) {
return;
}
StructWithList x=new StructWithList();
x.getVarList().add("I");
x.getVarList().add("am");
x.getVarList().add("StructWithList");
StructWithList yOrig=new StructWithList();
yOrig.getVarList().add("Does");
yOrig.getVarList().add("StructWithList");
yOrig.getVarList().add("work");
Holder y=new Holder(yOrig);
Holder z=new Holder();
StructWithList ret;
if (testDocLiteral) {
ret=docClient.testStructWithList(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testStructWithList(x,y,z);
}
else {
ret=rpcClient.testStructWithList(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testStructWithList(): Incorrect value for inout param",x,y.value);
assertEquals("testStructWithList(): Incorrect value for out param",yOrig,z.value);
assertEquals("testStructWithList(): Incorrect return value",x,ret);
}
x.getAttribList().add(1);
x.getAttribList().add(2);
x.getAttribList().add(3);
y.value=yOrig;
if (testDocLiteral) {
ret=docClient.testStructWithList(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testStructWithList(x,y,z);
}
else {
ret=rpcClient.testStructWithList(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testStructWithList(): Incorrect value for inout param",x,y.value);
assertEquals("testStructWithList(): Incorrect value for out param",yOrig,z.value);
assertEquals("testStructWithList(): Incorrect return value",x,ret);
}
yOrig.getAttribList().add(4);
yOrig.getAttribList().add(5);
yOrig.getAttribList().add(6);
y.value=yOrig;
if (testDocLiteral) {
ret=docClient.testStructWithList(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testStructWithList(x,y,z);
}
else {
ret=rpcClient.testStructWithList(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testStructWithList(): Incorrect value for inout param",x,y.value);
assertEquals("testStructWithList(): Incorrect value for out param",yOrig,z.value);
assertEquals("testStructWithList(): Incorrect return value",x,ret);
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testEmptyStruct() throws Exception {
if (!shouldRunTest("EmptyStruct")) {
return;
}
EmptyStruct x=new EmptyStruct();
EmptyStruct yOrig=new EmptyStruct();
Holder y=new Holder(yOrig);
Holder z=new Holder();
EmptyStruct ret;
if (testDocLiteral) {
ret=docClient.testEmptyStruct(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testEmptyStruct(x,y,z);
}
else {
ret=rpcClient.testEmptyStruct(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testEmptyStruct(): Null value for inout param",notNull(x,y.value));
assertTrue("testEmptyStruct(): Null value for out param",notNull(yOrig,z.value));
assertTrue("testEmptyStruct(): Null return value",notNull(x,ret));
}
DerivedStructBaseEmpty derivedX=new DerivedStructBaseEmpty();
derivedX.setVarFloatExt(-3.14f);
derivedX.setVarStringExt("DerivedStruct-x");
derivedX.setAttrString("DerivedAttr-x");
DerivedStructBaseEmpty derivedY=new DerivedStructBaseEmpty();
derivedY.setVarFloatExt(1.414f);
derivedY.setVarStringExt("DerivedStruct-y");
derivedY.setAttrString("DerivedAttr-y");
y=new Holder(derivedY);
z=new Holder();
if (testDocLiteral) {
ret=docClient.testEmptyStruct(derivedX,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testEmptyStruct(derivedX,y,z);
}
else {
ret=rpcClient.testEmptyStruct(derivedX,y,z);
}
if (!perfTestOnly) {
assertTrue("testEmptyStruct(): Null value for inout param",notNull(derivedX,y.value));
assertTrue("testEmptyStruct(): Null value for out param",notNull(derivedY,z.value));
assertTrue("testEmptyStruct(): Null return value",notNull(derivedX,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testStructWithSubstitutionGroup() throws Exception {
if (!shouldRunTest("StructWithSubstitutionGroup")) {
return;
}
SgBaseTypeA baseA=new SgBaseTypeA();
baseA.setVarInt(new BigInteger("1"));
SgDerivedTypeB derivedB=new SgDerivedTypeB();
derivedB.setVarInt(new BigInteger("32"));
derivedB.setVarString("foo");
ObjectFactory objectFactory=new ObjectFactory();
StructWithSubstitutionGroup x=new StructWithSubstitutionGroup();
JAXBElement extends SgBaseTypeA> elementA=objectFactory.createSg01BaseElementA(baseA);
x.setSg01BaseElementA(elementA);
StructWithSubstitutionGroup yOrig=new StructWithSubstitutionGroup();
JAXBElement extends SgBaseTypeA> elementB=objectFactory.createSg01DerivedElementB(derivedB);
yOrig.setSg01BaseElementA(elementB);
Holder y=new Holder(yOrig);
Holder z=new Holder();
StructWithSubstitutionGroup ret;
if (testDocLiteral) {
ret=docClient.testStructWithSubstitutionGroup(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testStructWithSubstitutionGroup(x,y,z);
}
else {
ret=rpcClient.testStructWithSubstitutionGroup(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testStructWithSubstitutionGroup(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testStructWithSubstitutionGroup(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testStructWithSubstitutionGroup(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier InternalCallVerifier NullVerifier
@Test public void testDocument() throws Exception {
if (!shouldRunTest("Document")) {
return;
}
Document x=new Document();
x.setValue("content-x");
x.setID("Hello There");
Document yOrig=new Document();
yOrig.setID("Cheerio");
yOrig.setValue("content-y");
Holder y=new Holder(yOrig);
Holder z=new Holder();
Document ret;
if (testDocLiteral) {
ret=docClient.testDocument(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testDocument(x,y,z);
}
else {
ret=rpcClient.testDocument(x,y,z);
}
if (!perfTestOnly) {
equals("testDocument(): Incorrect value for inout param",x,y.value);
equals("testDocument(): Incorrect value for out param",yOrig,z.value);
equals("testDocument(): Incorrect return value",x,ret);
}
x=new Document();
yOrig=new Document();
x.setValue("content-x");
yOrig.setValue("content-y");
x.setID(null);
yOrig.setID(null);
y=new Holder(yOrig);
z=new Holder();
if (testDocLiteral) {
ret=docClient.testDocument(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testDocument(x,y,z);
}
else {
ret=rpcClient.testDocument(x,y,z);
}
if (!perfTestOnly) {
equals("testDocument(): Incorrect value for inout param",x,y.value);
equals("testDocument(): Incorrect value for out param",yOrig,z.value);
equals("testDocument(): Incorrect return value",x,ret);
assertNull(y.value.getID());
assertNull(ret.getID());
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testSimpleChoice() throws Exception {
if (!shouldRunTest("SimpleChoice")) {
return;
}
SimpleChoice x=new SimpleChoice();
x.setVarFloat(-3.14f);
SimpleChoice yOrig=new SimpleChoice();
yOrig.setVarString("Cheerio");
Holder y=new Holder(yOrig);
Holder z=new Holder();
SimpleChoice ret;
if (testDocLiteral) {
ret=docClient.testSimpleChoice(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testSimpleChoice(x,y,z);
}
else {
ret=rpcClient.testSimpleChoice(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testSimpleChoice(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testSimpleChoice(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testSimpleChoice(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testCompoundArray() throws Exception {
if (!shouldRunTest("CompoundArray")) {
return;
}
CompoundArray x=new CompoundArray();
x.getArray1().addAll(Arrays.asList("AAA","BBB","CCC"));
x.getArray2().addAll(Arrays.asList("aaa","bbb","ccc"));
CompoundArray yOrig=new CompoundArray();
yOrig.getArray1().addAll(Arrays.asList("XXX","YYY","ZZZ"));
yOrig.getArray2().addAll(Arrays.asList("xxx","yyy","zzz"));
Holder y=new Holder(yOrig);
Holder z=new Holder();
CompoundArray ret;
if (testDocLiteral) {
ret=docClient.testCompoundArray(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testCompoundArray(x,y,z);
}
else {
ret=rpcClient.testCompoundArray(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testCompoundArray(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testCompoundArray(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testCompoundArray(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testStructWithOptionals() throws Exception {
if (!shouldRunTest("StructWithOptionals")) {
return;
}
StructWithOptionals x=new StructWithOptionals();
StructWithOptionals yOrig=new StructWithOptionals();
yOrig.setVarFloat(new Float(1.414f));
yOrig.setVarInt(new Integer(13));
yOrig.setVarString("Cheerio");
Holder y=new Holder(yOrig);
Holder z=new Holder();
StructWithOptionals ret;
if (testDocLiteral) {
ret=docClient.testStructWithOptionals(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testStructWithOptionals(x,y,z);
}
else {
ret=rpcClient.testStructWithOptionals(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testStructWithOptionals(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testStructWithOptionals(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testStructWithOptionals(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier IterativeVerifier BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testFixedArray() throws Exception {
if (!shouldRunTest("FixedArray")) {
return;
}
FixedArray x=new FixedArray();
x.getItem().addAll(Arrays.asList(Integer.MIN_VALUE,0,Integer.MAX_VALUE));
FixedArray yOrig=new FixedArray();
yOrig.getItem().addAll(Arrays.asList(-1,0,1));
Holder y=new Holder(yOrig);
Holder z=new Holder();
FixedArray ret;
if (testDocLiteral) {
ret=docClient.testFixedArray(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testFixedArray(x,y,z);
}
else {
ret=rpcClient.testFixedArray(x,y,z);
}
if (!perfTestOnly) {
for (int i=0; i < 3; i++) {
assertEquals("testFixedArray(): Incorrect value for inout param",x.getItem().get(i),y.value.getItem().get(i));
assertEquals("testFixedArray(): Incorrect value for out param",yOrig.getItem().get(i),z.value.getItem().get(i));
assertEquals("testFixedArray(): Incorrect return value",x.getItem().get(i),ret.getItem().get(i));
}
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testRecOuterType() throws Exception {
if (!shouldRunTest("RecOuterType")) {
return;
}
RecMostInnerType mitx=new RecMostInnerType();
RecMostInnerType mity=new RecMostInnerType();
RecMostInnerNextType mitxNext=new RecMostInnerNextType();
RecMostInnerNextType mityNext=new RecMostInnerNextType();
mitx.setRecMostInnerNext(mitxNext);
mity.setRecMostInnerNext(mityNext);
RecInnerType itx=new RecInnerType();
RecInnerType ity=new RecInnerType();
RecInnerNextType itxNext=new RecInnerNextType();
RecInnerNextType ityNext=new RecInnerNextType();
itx.setRecInnerNext(itxNext);
ity.setRecInnerNext(ityNext);
RecOuterType otx=new RecOuterType();
RecOuterType oty=new RecOuterType();
RecOuterNextType otxNext=new RecOuterNextType();
RecOuterNextType otyNext=new RecOuterNextType();
otx.setRecOuterNext(otxNext);
oty.setRecOuterNext(otyNext);
mitx.setVarInt(11);
mity.setVarInt(12);
mitxNext.getRecMostInner().add(mity);
itx.setVarInt(21);
ity.setVarInt(22);
itxNext.getRecInner().add(ity);
itx.getRecMostInner().add(mitx);
otx.setVarInt(31);
oty.setVarInt(32);
otxNext.getRecOuter().add(oty);
otx.getRecInner().add(itx);
otx.getRecMostInner().add(mitx);
Holder yh=new Holder(oty);
Holder zh=new Holder();
RecOuterType ret;
if (testDocLiteral) {
ret=docClient.testRecOuterType(otx,yh,zh);
}
else if (testXMLBinding) {
ret=xmlClient.testRecOuterType(otx,yh,zh);
}
else {
ret=rpcClient.testRecOuterType(otx,yh,zh);
}
if (!perfTestOnly) {
assertTrue("testRecOuterType(): Incorrect value for inout param",equals(otx,yh.value));
assertTrue("testRecOuterType(): Incorrect value for inout param",equals(oty,zh.value));
assertTrue("testRecOuterType(): Incorrect value for inout param",equals(ret,otx));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testExtColourEnum() throws Exception {
if (!shouldRunTest("ExtColourEnum")) {
return;
}
ExtColourEnum x=new ExtColourEnum();
x.setAttrib1(new Integer(1));
x.setAttrib2("Ax");
x.setValue(ColourEnum.fromValue("RED"));
ExtColourEnum yOrig=new ExtColourEnum();
yOrig.setAttrib1(new Integer(10));
yOrig.setAttrib2("Ay");
yOrig.setValue(ColourEnum.fromValue("GREEN"));
Holder y=new Holder(yOrig);
Holder z=new Holder();
ExtColourEnum ret;
if (testDocLiteral) {
ret=docClient.testExtColourEnum(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testExtColourEnum(x,y,z);
}
else {
ret=rpcClient.testExtColourEnum(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testExtColourEnum(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testExtColourEnum(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testExtColourEnum(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testChoiceWithSubstitutionGroupNil() throws Exception {
if (!shouldRunTest("ChoiceWithSubstitutionGroupNil")) {
return;
}
ObjectFactory objectFactory=new ObjectFactory();
ChoiceWithSubstitutionGroupNil x=new ChoiceWithSubstitutionGroupNil();
JAXBElement varInt=objectFactory.createChoiceWithSubstitutionGroupNilVarInt(null);
x.setVarInt(varInt);
ChoiceWithSubstitutionGroupNil yOrig=new ChoiceWithSubstitutionGroupNil();
JAXBElement extends SgBaseTypeA> elementA=objectFactory.createSg04NillableBaseElementA(null);
yOrig.setSg04NillableBaseElementA(elementA);
Holder y=new Holder(yOrig);
Holder z=new Holder();
ChoiceWithSubstitutionGroupNil ret;
if (testDocLiteral) {
ret=docClient.testChoiceWithSubstitutionGroupNil(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testChoiceWithSubstitutionGroupNil(x,y,z);
}
else {
ret=rpcClient.testChoiceWithSubstitutionGroupNil(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testChoiceWithSubstitutionGroupNil(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testChoiceWithSubstitutionGroupNil(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testChoiceWithSubstitutionGroupNil(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier IterativeVerifier BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testNestedArray() throws Exception {
if (!shouldRunTest("NestedArray")) {
return;
}
String[][] xs={{"AAA","BBB","CCC"},{"aaa","bbb","ccc"},{"a_a_a","b_b_b","c_c_c"}};
String[][] ys={{"XXX","YYY","ZZZ"},{"xxx","yyy","zzz"},{"x_x_x","y_y_y","z_z_z"}};
NestedArray x=new NestedArray();
NestedArray yOrig=new NestedArray();
List xList=x.getSubarray();
List yList=yOrig.getSubarray();
for (int i=0; i < 3; i++) {
UnboundedArray xx=new UnboundedArray();
xx.getItem().addAll(Arrays.asList(xs[i]));
xList.add(xx);
UnboundedArray yy=new UnboundedArray();
yy.getItem().addAll(Arrays.asList(ys[i]));
yList.add(yy);
}
Holder y=new Holder(yOrig);
Holder z=new Holder();
NestedArray ret;
if (testDocLiteral) {
ret=docClient.testNestedArray(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testNestedArray(x,y,z);
}
else {
ret=rpcClient.testNestedArray(x,y,z);
}
if (!perfTestOnly) {
for (int i=0; i < 3; i++) {
for (int j=0; j < 3; j++) {
assertEquals("testNestedArray(): Incorrect value for inout param",x.getSubarray().get(i).getItem().get(j),y.value.getSubarray().get(i).getItem().get(j));
assertEquals("testNestedArray(): Incorrect value for out param",yOrig.getSubarray().get(i).getItem().get(j),z.value.getSubarray().get(i).getItem().get(j));
assertEquals("testNestedArray(): Incorrect return value",x.getSubarray().get(i).getItem().get(j),ret.getSubarray().get(i).getItem().get(j));
}
}
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testStructWithSubstitutionGroupNil() throws Exception {
if (!shouldRunTest("StructWithSubstitutionGroupNil")) {
return;
}
StructWithSubstitutionGroupNil x=new StructWithSubstitutionGroupNil();
ObjectFactory objectFactory=new ObjectFactory();
JAXBElement extends SgBaseTypeA> element=objectFactory.createSg04NillableBaseElementA(null);
x.setSg04NillableBaseElementA(element);
StructWithSubstitutionGroupNil yOrig=new StructWithSubstitutionGroupNil();
element=objectFactory.createSg04NillableBaseElementA(null);
yOrig.setSg04NillableBaseElementA(element);
Holder y=new Holder(yOrig);
Holder z=new Holder();
StructWithSubstitutionGroupNil ret;
if (testDocLiteral) {
ret=docClient.testStructWithSubstitutionGroupNil(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testStructWithSubstitutionGroupNil(x,y,z);
}
else {
ret=rpcClient.testStructWithSubstitutionGroupNil(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testStructWithSubstitutionGroupNil(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testStructWithSubstitutionGroupNil(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testStructWithSubstitutionGroupNil(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testUnionSimpleContent() throws Exception {
if (!shouldRunTest("UnionSimpleContent")) {
return;
}
UnionSimpleContent x=new UnionSimpleContent();
x.setValue("5");
UnionSimpleContent yOrig=new UnionSimpleContent();
yOrig.setValue("-7");
Holder y=new Holder(yOrig);
Holder z=new Holder();
UnionSimpleContent ret;
if (testDocLiteral) {
ret=docClient.testUnionSimpleContent(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testUnionSimpleContent(x,y,z);
}
else {
ret=rpcClient.testUnionSimpleContent(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testUnionSimpleContent(): Incorrect value for inout param",x,y.value);
assertEquals("testUnionSimpleContent(): Incorrect value for out param",yOrig,z.value);
assertEquals("testUnionSimpleContent(): Incorrect return value",x,ret);
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testRecursiveStructArray() throws Exception {
if (!shouldRunTest("RecursiveStructArray")) {
return;
}
RecursiveStruct xtmp=new RecursiveStruct();
xtmp.setVarFloat(0.14f);
xtmp.setVarInt(4);
xtmp.setVarString("tmp-x");
xtmp.setVarStructArray(new RecursiveStructArray());
RecursiveStruct ytmp=new RecursiveStruct();
ytmp.setVarFloat(0.414f);
ytmp.setVarInt(1);
ytmp.setVarString("tmp-y");
ytmp.setVarStructArray(new RecursiveStructArray());
RecursiveStructArray x=new RecursiveStructArray();
x.getItem().add(xtmp);
x.getItem().add(ytmp);
RecursiveStructArray yOrig=new RecursiveStructArray();
yOrig.getItem().add(ytmp);
yOrig.getItem().add(xtmp);
Holder y=new Holder(yOrig);
Holder z=new Holder();
RecursiveStructArray ret;
if (testDocLiteral) {
ret=docClient.testRecursiveStructArray(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testRecursiveStructArray(x,y,z);
}
else {
ret=rpcClient.testRecursiveStructArray(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testRecursiveStructArray(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testRecursiveStructArray(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testRecursiveStructArray(): Incorrect return value",equals(ret,x));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testStructWithNillables() throws Exception {
if (!shouldRunTest("StructWithNillables")) {
return;
}
StructWithNillables x=new StructWithNillables();
StructWithNillables yOrig=new StructWithNillables();
yOrig.setVarFloat(new Float(1.414f));
yOrig.setVarInt(new Integer(13));
yOrig.setVarString("Cheerio");
Holder y=new Holder(yOrig);
Holder z=new Holder();
StructWithNillables ret;
if (testDocLiteral) {
ret=docClient.testStructWithNillables(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testStructWithNillables(x,y,z);
}
else {
ret=rpcClient.testStructWithNillables(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testStructWithNillables(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testStructWithNillables(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testStructWithNillables(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier IterativeVerifier BranchVerifier BooleanVerifier InternalCallVerifier EqualityVerifier PublicFieldVerifier HybridVerifier
@Test public void testBoundedArray() throws Exception {
if (!shouldRunTest("BoundedArray")) {
return;
}
BoundedArray x=new BoundedArray();
x.getItem().addAll(Arrays.asList(-100.00f,0f,100.00f));
BoundedArray yOrig=new BoundedArray();
yOrig.getItem().addAll(Arrays.asList(-1f,0f,1f));
Holder y=new Holder(yOrig);
Holder z=new Holder();
BoundedArray ret;
if (testDocLiteral) {
ret=docClient.testBoundedArray(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testBoundedArray(x,y,z);
}
else {
ret=rpcClient.testBoundedArray(x,y,z);
}
if (!perfTestOnly) {
float delta=0.0f;
int xSize=x.getItem().size();
int ySize=y.value.getItem().size();
int zSize=z.value.getItem().size();
int retSize=ret.getItem().size();
assertTrue("testBoundedArray() array size incorrect",xSize == ySize && ySize == zSize && zSize == retSize && xSize == 3);
for (int i=0; i < xSize; i++) {
assertEquals("testBoundedArray(): Incorrect value for inout param",x.getItem().get(i),y.value.getItem().get(i),delta);
assertEquals("testBoundedArray(): Incorrect value for out param",yOrig.getItem().get(i),z.value.getItem().get(i),delta);
assertEquals("testBoundedArray(): Incorrect return value",x.getItem().get(i),ret.getItem().get(i),delta);
}
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testRecElType() throws Exception {
if (!shouldRunTest("RecElType")) {
return;
}
RecElType x=new RecElType();
RecElType y=new RecElType();
RecElNextType xn=new RecElNextType();
RecElNextType yn=new RecElNextType();
y.setVarInt(123);
y.setRecElNext(yn);
xn.getRecEl().add(y);
x.setVarInt(456);
x.setRecElNext(xn);
Holder yh=new Holder(y);
Holder zh=new Holder();
RecElType ret;
if (testDocLiteral) {
ret=docClient.testRecElType(x,yh,zh);
}
else if (testXMLBinding) {
ret=xmlClient.testRecElType(x,yh,zh);
}
else {
ret=rpcClient.testRecElType(x,yh,zh);
}
if (!perfTestOnly) {
assertTrue("testRecElType(): Incorrect value for inout param",equals(x,yh.value));
assertTrue("testRecElType(): Incorrect value for inout param",equals(y,zh.value));
assertTrue("testRecElType(): Incorrect value for inout param",equals(ret,x));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testRecursiveStruct() throws Exception {
if (!shouldRunTest("RecursiveStruct")) {
return;
}
RecursiveStruct xtmp=new RecursiveStruct();
xtmp.setVarFloat(0.14f);
xtmp.setVarInt(4);
xtmp.setVarString("tmp-x");
xtmp.setVarStructArray(new RecursiveStructArray());
RecursiveStruct ytmp=new RecursiveStruct();
ytmp.setVarFloat(0.414f);
ytmp.setVarInt(1);
ytmp.setVarString("tmp-y");
ytmp.setVarStructArray(new RecursiveStructArray());
RecursiveStructArray arr=new RecursiveStructArray();
arr.getItem().add(xtmp);
arr.getItem().add(ytmp);
RecursiveStruct x=new RecursiveStruct();
x.setVarFloat(3.14f);
x.setVarInt(42);
x.setVarString("RecStruct-x");
x.setVarStructArray(arr);
RecursiveStruct yOrig=new RecursiveStruct();
yOrig.setVarFloat(1.414f);
yOrig.setVarInt(13);
yOrig.setVarString("RecStruct-y");
yOrig.setVarStructArray(arr);
Holder y=new Holder(yOrig);
Holder z=new Holder();
RecursiveStruct ret;
if (testDocLiteral) {
ret=docClient.testRecursiveStruct(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testRecursiveStruct(x,y,z);
}
else {
ret=rpcClient.testRecursiveStruct(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testRecursiveStruct(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testRecursiveStruct(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testRecursiveStruct(): Incorrect return value",equals(ret,x));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testChoiceArray() throws Exception {
if (!shouldRunTest("ChoiceArray")) {
return;
}
RecursiveUnion tmp1=new RecursiveUnion();
tmp1.setVarString("RecusiveUnion-1");
RecursiveUnion tmp2=new RecursiveUnion();
tmp2.setVarString("RecusiveUnion-2");
ChoiceArray x=new ChoiceArray();
x.getItem().add(tmp1);
x.getItem().add(tmp2);
ChoiceArray yOrig=new ChoiceArray();
yOrig.getItem().add(tmp2);
yOrig.getItem().add(tmp1);
Holder y=new Holder(yOrig);
Holder z=new Holder();
ChoiceArray ret;
if (testDocLiteral) {
ret=docClient.testChoiceArray(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testChoiceArray(x,y,z);
}
else {
ret=rpcClient.testChoiceArray(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testChoiceArray(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testChoiceArray(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testChoiceArray(): Incorrect return value",equals(ret,x));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testChoiceWithSubstitutionGroup() throws Exception {
if (!shouldRunTest("ChoiceWithSubstitutionGroup")) {
return;
}
SgBaseTypeA baseA=new SgBaseTypeA();
baseA.setVarInt(new BigInteger("1"));
ObjectFactory objectFactory=new ObjectFactory();
JAXBElement extends SgBaseTypeA> elementA=objectFactory.createSg01BaseElementA(baseA);
SgDerivedTypeB derivedB=new SgDerivedTypeB();
derivedB.setVarInt(new BigInteger("32"));
derivedB.setVarString("SgDerivedTypeB");
JAXBElement extends SgBaseTypeA> elementB=objectFactory.createSg01DerivedElementB(derivedB);
ChoiceWithSubstitutionGroup x=new ChoiceWithSubstitutionGroup();
x.setSg01BaseElementA(elementA);
ChoiceWithSubstitutionGroup yOrig=new ChoiceWithSubstitutionGroup();
yOrig.setSg01BaseElementA(elementB);
Holder y=new Holder(yOrig);
Holder z=new Holder();
assertTrue("yoo: ",equals(y.value,y.value));
ChoiceWithSubstitutionGroup ret;
if (testDocLiteral) {
ret=docClient.testChoiceWithSubstitutionGroup(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testChoiceWithSubstitutionGroup(x,y,z);
}
else {
ret=rpcClient.testChoiceWithSubstitutionGroup(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testChoiceWithSubstitutionGroup(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testChoiceWithSubstitutionGroup(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testChoiceWithSubstitutionGroup(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testRecursiveUnion() throws Exception {
if (!shouldRunTest("RecursiveUnion")) {
return;
}
RecursiveUnion tmp1=new RecursiveUnion();
tmp1.setVarString("RecusiveUnion-1");
RecursiveUnion tmp2=new RecursiveUnion();
tmp2.setVarString("RecusiveUnion-2");
RecursiveUnionData xData=new RecursiveUnionData();
ChoiceArray xChoice=new ChoiceArray();
xChoice.getItem().add(tmp1);
xChoice.getItem().add(tmp2);
xData.setVarInt(5);
xData.setVarChoiceArray(xChoice);
RecursiveUnion x=new RecursiveUnion();
x.setVarChoice(xData);
RecursiveUnionData yData=new RecursiveUnionData();
ChoiceArray yChoice=new ChoiceArray();
yChoice.getItem().add(tmp1);
yChoice.getItem().add(tmp2);
yData.setVarInt(-5);
yData.setVarChoiceArray(yChoice);
RecursiveUnion yOrig=new RecursiveUnion();
yOrig.setVarChoice(yData);
Holder y=new Holder(yOrig);
Holder z=new Holder();
RecursiveUnion ret;
if (testDocLiteral) {
ret=docClient.testRecursiveUnion(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testRecursiveUnion(x,y,z);
}
else {
ret=rpcClient.testRecursiveUnion(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testRecursiveUnion(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testRecursiveUnion(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testRecursiveUnion(): Incorrect return value",equals(ret,x));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testExtBase64Binary() throws Exception {
if (!shouldRunTest("ExtBase64Binary")) {
return;
}
ExtBase64Binary x1=new ExtBase64Binary();
x1.setValue("base64a".getBytes());
x1.setId(1);
ExtBase64Binary y1=new ExtBase64Binary();
y1.setValue("base64b".getBytes());
y1.setId(2);
Holder y1Holder=new Holder(y1);
Holder z1=new Holder();
ExtBase64Binary ret;
if (testDocLiteral) {
ret=docClient.testExtBase64Binary(x1,y1Holder,z1);
}
else if (testXMLBinding) {
ret=xmlClient.testExtBase64Binary(x1,y1Holder,z1);
}
else {
ret=rpcClient.testExtBase64Binary(x1,y1Holder,z1);
}
if (!perfTestOnly) {
assertTrue("testExtBase64Binary(): Incorrect value for inout param",equals(x1,y1Holder.value));
assertTrue("testExtBase64Binary(): Incorrect value for out param",equals(y1,z1.value));
assertTrue("testExtBase64Binary(): Incorrect return value",equals(x1,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testStructWithSubstitutionGroupAbstract() throws Exception {
if (!shouldRunTest("StructWithSubstitutionGroupAbstract")) {
return;
}
SgDerivedTypeB derivedB=new SgDerivedTypeB();
derivedB.setVarInt(new BigInteger("32"));
derivedB.setVarString("foo");
ObjectFactory objectFactory=new ObjectFactory();
JAXBElement elementB=objectFactory.createSg03DerivedElementB(derivedB);
SgDerivedTypeC derivedC=new SgDerivedTypeC();
derivedC.setVarInt(new BigInteger("32"));
derivedC.setVarFloat(3.14f);
JAXBElement elementC=objectFactory.createSg03DerivedElementC(derivedC);
StructWithSubstitutionGroupAbstract x=new StructWithSubstitutionGroupAbstract();
x.setSg03AbstractBaseElementA(elementC);
StructWithSubstitutionGroupAbstract yOrig=new StructWithSubstitutionGroupAbstract();
yOrig.setSg03AbstractBaseElementA(elementB);
Holder y=new Holder(yOrig);
Holder z=new Holder();
StructWithSubstitutionGroupAbstract ret;
if (testDocLiteral) {
ret=docClient.testStructWithSubstitutionGroupAbstract(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testStructWithSubstitutionGroupAbstract(x,y,z);
}
else {
ret=rpcClient.testStructWithSubstitutionGroupAbstract(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testStructWithSubstitutionGroupAbstract(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testStructWithSubstitutionGroupAbstract(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testStructWithSubstitutionGroupAbstract(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier IterativeVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testUnboundedArray() throws Exception {
if (!shouldRunTest("UnboundedArray")) {
return;
}
UnboundedArray x=new UnboundedArray();
x.getItem().addAll(Arrays.asList("AAA","BBB","CCC"));
UnboundedArray yOrig=new UnboundedArray();
yOrig.getItem().addAll(Arrays.asList("XXX","YYY","ZZZ"));
Holder y=new Holder(yOrig);
Holder z=new Holder();
UnboundedArray ret;
if (testDocLiteral) {
ret=docClient.testUnboundedArray(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testUnboundedArray(x,y,z);
}
else {
ret=rpcClient.testUnboundedArray(x,y,z);
}
if (!perfTestOnly) {
for (int i=0; i < 3; i++) {
assertTrue("testUnboundedArray(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testUnboundedArray(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testUnboundedArray(): Incorrect return value",equals(x,ret));
}
}
}
APIUtilityVerifier BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testExtendsSimpleContent() throws Exception {
if (!shouldRunTest("ExtendsSimpleContent")) {
return;
}
ExtendsSimpleContent x=new ExtendsSimpleContent();
x.setValue("foo");
ExtendsSimpleContent yOriginal=new ExtendsSimpleContent();
yOriginal.setValue("bar");
Holder y=new Holder(yOriginal);
Holder z=new Holder();
ExtendsSimpleContent ret;
if (testDocLiteral) {
ret=docClient.testExtendsSimpleContent(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testExtendsSimpleContent(x,y,z);
}
else {
ret=rpcClient.testExtendsSimpleContent(x,y,z);
}
if (!perfTestOnly) {
assertEquals(x.getValue(),y.value.getValue());
assertEquals(yOriginal.getValue(),z.value.getValue());
assertEquals(x.getValue(),ret.getValue());
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testStructWithMultipleSubstitutionGroups() throws Exception {
if (!shouldRunTest("StructWithMultipleSubstitutionGroups")) {
return;
}
SgBaseTypeA baseA=new SgBaseTypeA();
baseA.setVarInt(new BigInteger("1"));
SgDerivedTypeB derivedB=new SgDerivedTypeB();
derivedB.setVarInt(new BigInteger("32"));
derivedB.setVarString("y-SgDerivedTypeB");
SgDerivedTypeC derivedC=new SgDerivedTypeC();
derivedC.setVarInt(new BigInteger("1"));
derivedC.setVarFloat(3.14f);
ObjectFactory objectFactory=new ObjectFactory();
JAXBElement extends SgBaseTypeA> x1=objectFactory.createSg01DerivedElementB(derivedB);
JAXBElement extends SgBaseTypeA> x2=objectFactory.createSg02BaseElementA(baseA);
JAXBElement extends SgBaseTypeA> y1=objectFactory.createSg01DerivedElementB(derivedB);
JAXBElement extends SgBaseTypeA> y2=objectFactory.createSg02DerivedElementC(derivedC);
StructWithMultipleSubstitutionGroups x=new StructWithMultipleSubstitutionGroups();
x.setVarFloat(111.1f);
x.setVarInt(new BigInteger("100"));
x.setVarString("x-varString");
x.setSg01BaseElementA(x1);
x.setSg02BaseElementA(x2);
StructWithMultipleSubstitutionGroups yOrig=new StructWithMultipleSubstitutionGroups();
yOrig.setVarFloat(1.1f);
yOrig.setVarInt(new BigInteger("10"));
yOrig.setVarString("y-varString");
yOrig.setSg01BaseElementA(y1);
yOrig.setSg02BaseElementA(y2);
Holder y=new Holder(yOrig);
Holder z=new Holder();
StructWithMultipleSubstitutionGroups ret;
if (testDocLiteral) {
ret=docClient.testStructWithMultipleSubstitutionGroups(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testStructWithMultipleSubstitutionGroups(x,y,z);
}
else {
ret=rpcClient.testStructWithMultipleSubstitutionGroups(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testStructWithMultipleSubstitutionGroups(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testStructWithMultipleSubstitutionGroups(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testStructWithMultipleSubstitutionGroups(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testExtendsSimpleType() throws Exception {
if (!shouldRunTest("ExtendsSimpleType")) {
return;
}
ExtendsSimpleType x=new ExtendsSimpleType();
x.setValue("foo");
ExtendsSimpleType yOriginal=new ExtendsSimpleType();
yOriginal.setValue("bar");
Holder y=new Holder(yOriginal);
Holder z=new Holder();
ExtendsSimpleType ret;
if (testDocLiteral) {
ret=docClient.testExtendsSimpleType(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testExtendsSimpleType(x,y,z);
}
else {
ret=rpcClient.testExtendsSimpleType(x,y,z);
}
if (!perfTestOnly) {
assertEquals(x.getValue(),y.value.getValue());
assertEquals(yOriginal.getValue(),z.value.getValue());
assertEquals(x.getValue(),ret.getValue());
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testAnonymousStruct() throws Exception {
if (!shouldRunTest("AnonymousStruct")) {
return;
}
AnonymousStruct x=new AnonymousStruct();
x.setVarInt(100);
x.setVarString("hello");
x.setVarFloat(1.1f);
AnonymousStruct yOrig=new AnonymousStruct();
yOrig.setVarInt(11);
yOrig.setVarString("world");
yOrig.setVarFloat(10.1f);
Holder y=new Holder(yOrig);
Holder z=new Holder();
AnonymousStruct ret;
if (testDocLiteral) {
ret=docClient.testAnonymousStruct(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testAnonymousStruct(x,y,z);
}
else {
ret=rpcClient.testAnonymousStruct(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testAnonymousStruct(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testAnonymousStruct(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testAnonymousStruct(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testStructWithUnion() throws Exception {
if (!shouldRunTest("StructWithUnion")) {
return;
}
StructWithUnion x=new StructWithUnion();
x.setVarUnion("999");
StructWithUnion yOrig=new StructWithUnion();
yOrig.setVarUnion("-999");
Holder y=new Holder(yOrig);
Holder z=new Holder();
StructWithUnion ret;
if (testDocLiteral) {
ret=docClient.testStructWithUnion(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testStructWithUnion(x,y,z);
}
else {
ret=rpcClient.testStructWithUnion(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testStructWithUnion(): Incorrect value for inout param",x,y.value);
assertEquals("testStructWithUnion(): Incorrect value for out param",yOrig,z.value);
assertEquals("testStructWithUnion(): Incorrect return value",x,ret);
}
x.setAttribUnion("99");
y.value=yOrig;
if (testDocLiteral) {
ret=docClient.testStructWithUnion(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testStructWithUnion(x,y,z);
}
else {
ret=rpcClient.testStructWithUnion(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testStructWithUnion(): Incorrect value for inout param",x,y.value);
assertEquals("testStructWithUnion(): Incorrect value for out param",yOrig,z.value);
assertEquals("testStructWithUnion(): Incorrect return value",x,ret);
}
yOrig.setAttribUnion("-99");
y.value=yOrig;
if (testDocLiteral) {
ret=docClient.testStructWithUnion(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testStructWithUnion(x,y,z);
}
else {
ret=rpcClient.testStructWithUnion(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testStructWithUnion(): Incorrect value for inout param",x,y.value);
assertEquals("testStructWithUnion(): Incorrect value for out param",yOrig,z.value);
assertEquals("testStructWithUnion(): Incorrect return value",x,ret);
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testNestedStruct() throws Exception {
if (!shouldRunTest("NestedStruct")) {
return;
}
SimpleStruct xs=new SimpleStruct();
xs.setVarFloat(30.14);
xs.setVarInt(new BigInteger("420"));
xs.setVarString("NESTED Hello There");
NestedStruct x=new NestedStruct();
x.setVarFloat(new BigDecimal("3.14"));
x.setVarInt(42);
x.setVarString("Hello There");
x.setVarEmptyStruct(new EmptyStruct());
x.setVarStruct(xs);
SimpleStruct ys=new SimpleStruct();
ys.setVarFloat(10.414);
ys.setVarInt(new BigInteger("130"));
ys.setVarString("NESTED Cheerio");
NestedStruct yOrig=new NestedStruct();
yOrig.setVarFloat(new BigDecimal("1.414"));
yOrig.setVarInt(13);
yOrig.setVarString("Cheerio");
yOrig.setVarEmptyStruct(new EmptyStruct());
yOrig.setVarStruct(ys);
Holder y=new Holder(yOrig);
Holder z=new Holder();
NestedStruct ret;
if (testDocLiteral) {
ret=docClient.testNestedStruct(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testNestedStruct(x,y,z);
}
else {
ret=rpcClient.testNestedStruct(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testNestedStruct(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testNestedStruct(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testNestedStruct(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testSimpleStruct() throws Exception {
if (!shouldRunTest("SimpleStruct")) {
return;
}
SimpleStruct x=new SimpleStruct();
x.setVarFloat(3.14f);
x.setVarInt(new BigInteger("42"));
x.setVarString("Hello There");
SimpleStruct yOrig=new SimpleStruct();
yOrig.setVarFloat(1.414f);
yOrig.setVarInt(new BigInteger("13"));
yOrig.setVarString("Cheerio");
Holder y=new Holder(yOrig);
Holder z=new Holder();
SimpleStruct ret;
if (testDocLiteral) {
ret=docClient.testSimpleStruct(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testSimpleStruct(x,y,z);
}
else {
ret=rpcClient.testSimpleStruct(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testSimpleStruct(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testSimpleStruct(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testSimpleStruct(): Incorrect return value",equals(x,ret));
}
}
Class: org.apache.cxf.systest.type_test.AbstractTypeTestClient3 APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testDerivedStructBaseStruct() throws Exception {
if (!shouldRunTest("DerivedStructBaseStruct")) {
return;
}
DerivedStructBaseStruct x=new DerivedStructBaseStruct();
x.setVarFloat(3.14f);
x.setVarInt(new BigInteger("42"));
x.setVarString("BaseStruct-x");
x.setVarAttrString("BaseStructAttr-x");
x.setVarFloatExt(-3.14f);
x.setVarStringExt("DerivedStruct-x");
x.setAttrString1("DerivedAttr1-x");
x.setAttrString2("DerivedAttr2-x");
DerivedStructBaseStruct yOrig=new DerivedStructBaseStruct();
yOrig.setVarFloat(-9.14f);
yOrig.setVarInt(new BigInteger("10"));
yOrig.setVarString("BaseStruct-y");
yOrig.setVarAttrString("BaseStructAttr-y");
yOrig.setVarFloatExt(1.414f);
yOrig.setVarStringExt("DerivedStruct-y");
yOrig.setAttrString1("DerivedAttr1-y");
yOrig.setAttrString2("DerivedAttr2-y");
Holder y=new Holder(yOrig);
Holder z=new Holder();
DerivedStructBaseStruct ret;
if (testDocLiteral) {
ret=docClient.testDerivedStructBaseStruct(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testDerivedStructBaseStruct(x,y,z);
}
else {
ret=rpcClient.testDerivedStructBaseStruct(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testDerivedStructBaseStruct(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testDerivedStructBaseStruct(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testDerivedStructBaseStruct(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testDerivedStructBaseEmpty() throws Exception {
if (!shouldRunTest("DerivedStructBaseEmpty")) {
return;
}
DerivedStructBaseEmpty x=new DerivedStructBaseEmpty();
x.setVarFloatExt(-3.14f);
x.setVarStringExt("DerivedStruct-x");
x.setAttrString("DerivedAttr-x");
DerivedStructBaseEmpty yOrig=new DerivedStructBaseEmpty();
yOrig.setVarFloatExt(1.414f);
yOrig.setVarStringExt("DerivedStruct-y");
yOrig.setAttrString("DerivedAttr-y");
Holder y=new Holder(yOrig);
Holder z=new Holder();
DerivedStructBaseEmpty ret;
if (testDocLiteral) {
ret=docClient.testDerivedStructBaseEmpty(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testDerivedStructBaseEmpty(x,y,z);
}
else {
ret=rpcClient.testDerivedStructBaseEmpty(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testDerivedStructBaseEmpty(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testDerivedStructBaseEmpty(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testDerivedStructBaseEmpty(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testChoiceWithGroupSeq() throws Exception {
if (!shouldRunTest("ChoiceWithGroupSeq")) {
return;
}
ChoiceWithGroupSeq x=new ChoiceWithGroupSeq();
x.setVarInt(100);
x.setVarString("hello");
x.setVarFloat(1.1f);
ChoiceWithGroupSeq yOrig=new ChoiceWithGroupSeq();
yOrig.setVarOtherInt(11);
yOrig.setVarOtherString("world");
yOrig.setVarOtherFloat(10.1f);
Holder y=new Holder(yOrig);
Holder z=new Holder();
ChoiceWithGroupSeq ret;
if (testDocLiteral) {
ret=docClient.testChoiceWithGroupSeq(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testChoiceWithGroupSeq(x,y,z);
}
else {
ret=rpcClient.testChoiceWithGroupSeq(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testChoiceWithGroupSeq(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testChoiceWithGroupSeq(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testChoiceWithGroupSeq(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testStructWithAnyAttribute() throws Exception {
if (!shouldRunTest("StructWithAnyAttribute")) {
return;
}
QName xAt1Name=new QName("http://schemas.iona.com/type_test","at_one");
QName xAt2Name=new QName("http://schemas.iona.com/type_test","at_two");
QName yAt3Name=new QName("http://apache.org/type_test","at_thr");
QName yAt4Name=new QName("http://apache.org/type_test","at_fou");
StructWithAnyAttribute x=new StructWithAnyAttribute();
StructWithAnyAttribute y=new StructWithAnyAttribute();
x.setVarString("hello");
x.setVarInt(1000);
x.setAtString("hello attribute");
x.setAtInt(new Integer(2000));
y.setVarString("there");
y.setVarInt(1001);
y.setAtString("there attribute");
y.setAtInt(new Integer(2002));
Map xAttrMap=x.getOtherAttributes();
xAttrMap.put(xAt1Name,"one");
xAttrMap.put(xAt2Name,"two");
Map yAttrMap=y.getOtherAttributes();
yAttrMap.put(yAt3Name,"three");
yAttrMap.put(yAt4Name,"four");
Holder yh=new Holder(y);
Holder zh=new Holder();
StructWithAnyAttribute ret;
if (testDocLiteral) {
ret=docClient.testStructWithAnyAttribute(x,yh,zh);
}
else if (testXMLBinding) {
ret=xmlClient.testStructWithAnyAttribute(x,yh,zh);
}
else {
ret=rpcClient.testStructWithAnyAttribute(x,yh,zh);
}
if (!perfTestOnly) {
assertTrue("testStructWithAnyAttribute(): Incorrect value for inout param",equals(x,yh.value));
assertTrue("testStructWithAnyAttribute(): Incorrect value for out param",equals(y,zh.value));
assertTrue("testStructWithAnyAttribute(): Incorrect return value",equals(ret,x));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testStructWithBinary() throws Exception {
if (!shouldRunTest("StructWithBinary")) {
return;
}
StructWithBinary x=new StructWithBinary();
x.setBase64("base64Binary_x".getBytes());
x.setHex("hexBinary_x".getBytes());
StructWithBinary yOriginal=new StructWithBinary();
yOriginal.setBase64("base64Binary_y".getBytes());
yOriginal.setHex("hexBinary_y".getBytes());
Holder y=new Holder(yOriginal);
Holder z=new Holder();
StructWithBinary ret;
if (testDocLiteral) {
ret=docClient.testStructWithBinary(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testStructWithBinary(x,y,z);
}
else {
ret=rpcClient.testStructWithBinary(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testStructWithBinary(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testStructWithBinary(): Incorrect value for out param",equals(yOriginal,z.value));
assertTrue("testStructWithBinary(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testOccuringStruct1() throws Exception {
if (!shouldRunTest("OccuringStruct1")) {
return;
}
OccuringStruct1 x=new OccuringStruct1();
List theList=x.getVarFloatAndVarIntAndVarString();
theList.add(1.1f);
theList.add(2);
theList.add("xX");
OccuringStruct1 yOriginal=new OccuringStruct1();
theList=yOriginal.getVarFloatAndVarIntAndVarString();
theList.add(11.11f);
theList.add(22);
theList.add("yY");
Holder y=new Holder(yOriginal);
Holder z=new Holder();
OccuringStruct1 ret;
if (testDocLiteral) {
ret=docClient.testOccuringStruct1(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testOccuringStruct1(x,y,z);
}
else {
ret=rpcClient.testOccuringStruct1(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testOccuringStruct1(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testOccuringStruct1(): Incorrect value for out param",equals(yOriginal,z.value));
assertTrue("testOccuringStruct1(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testComplexTypeWithAttributeGroup() throws Exception {
if (!shouldRunTest("ComplexTypeWithAttributeGroup")) {
return;
}
ComplexTypeWithAttributeGroup x=new ComplexTypeWithAttributeGroup();
x.setAttrInt(new BigInteger("123"));
x.setAttrString("x123");
ComplexTypeWithAttributeGroup yOrig=new ComplexTypeWithAttributeGroup();
yOrig.setAttrInt(new BigInteger("456"));
yOrig.setAttrString("x456");
Holder y=new Holder(yOrig);
Holder z=new Holder();
ComplexTypeWithAttributeGroup ret;
if (testDocLiteral) {
ret=docClient.testComplexTypeWithAttributeGroup(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testComplexTypeWithAttributeGroup(x,y,z);
}
else {
ret=rpcClient.testComplexTypeWithAttributeGroup(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testComplexTypeWithAttributeGroup(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testComplexTypeWithAttributeGroup(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testComplexTypeWithAttributeGroup(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testOccuringStruct2() throws Exception {
if (!shouldRunTest("OccuringStruct2")) {
return;
}
OccuringStruct2 x=new OccuringStruct2();
x.setVarFloat(1.14f);
List theList=x.getVarIntAndVarString();
theList.add(0);
theList.add("x1");
theList.add(1);
theList.add("x2");
OccuringStruct2 yOriginal=new OccuringStruct2();
yOriginal.setVarFloat(3.14f);
theList=yOriginal.getVarIntAndVarString();
theList.add(42);
theList.add("the answer");
theList.add(6);
theList.add("hammer");
theList.add(2);
theList.add("anvil");
Holder y=new Holder(yOriginal);
Holder z=new Holder();
OccuringStruct2 ret;
if (testDocLiteral) {
ret=docClient.testOccuringStruct2(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testOccuringStruct2(x,y,z);
}
else {
ret=rpcClient.testOccuringStruct2(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testOccuringStruct2(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testOccuringStruct2(): Incorrect value for out param",equals(yOriginal,z.value));
assertTrue("testOccuringStruct2(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testDerivedChoiceBaseChoice() throws Exception {
if (!shouldRunTest("DerivedChoiceBaseChoice")) {
return;
}
DerivedChoiceBaseChoice x=new DerivedChoiceBaseChoice();
x.setVarString("BaseChoice-x");
x.setVarStringExt("DerivedChoice-x");
x.setAttrString("DerivedAttr-x");
DerivedChoiceBaseChoice yOrig=new DerivedChoiceBaseChoice();
yOrig.setVarFloat(-9.14f);
yOrig.setVarFloatExt(1.414f);
yOrig.setAttrString("DerivedAttr-y");
Holder y=new Holder(yOrig);
Holder z=new Holder();
DerivedChoiceBaseChoice ret;
if (testDocLiteral) {
ret=docClient.testDerivedChoiceBaseChoice(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testDerivedChoiceBaseChoice(x,y,z);
}
else {
ret=rpcClient.testDerivedChoiceBaseChoice(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testDerivedChoiceBaseChoice(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testDerivedChoiceBaseChoice(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testDerivedChoiceBaseChoice(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testSequenceWithGroupChoice() throws Exception {
if (!shouldRunTest("SequenceWithGroupChoice")) {
return;
}
SequenceWithGroupChoice x=new SequenceWithGroupChoice();
x.setVarFloat(1.1f);
x.setVarOtherString("world");
SequenceWithGroupChoice yOrig=new SequenceWithGroupChoice();
yOrig.setVarOtherFloat(2.2f);
yOrig.setVarString("world");
Holder y=new Holder(yOrig);
Holder z=new Holder();
SequenceWithGroupChoice ret;
if (testDocLiteral) {
ret=docClient.testSequenceWithGroupChoice(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testSequenceWithGroupChoice(x,y,z);
}
else {
ret=rpcClient.testSequenceWithGroupChoice(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testSequenceWithGroupChoice(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testSequenceWithGroupChoice(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testSequenceWithGroupChoice(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testDerivedChoiceBaseArray() throws Exception {
if (!shouldRunTest("DerivedChoiceBaseArray")) {
return;
}
DerivedChoiceBaseArray x=new DerivedChoiceBaseArray();
x.getItem().addAll(Arrays.asList("AAA","BBB","CCC"));
x.setVarStringExt("DerivedChoice-x");
x.setAttrStringExt("DerivedAttr-x");
DerivedChoiceBaseArray yOrig=new DerivedChoiceBaseArray();
yOrig.getItem().addAll(Arrays.asList("XXX","YYY","ZZZ"));
yOrig.setVarFloatExt(1.414f);
yOrig.setAttrStringExt("DerivedAttr-y");
Holder y=new Holder(yOrig);
Holder z=new Holder();
DerivedChoiceBaseArray ret;
if (testDocLiteral) {
ret=docClient.testDerivedChoiceBaseArray(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testDerivedChoiceBaseArray(x,y,z);
}
else {
ret=rpcClient.testDerivedChoiceBaseArray(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testDerivedChoiceBaseArray(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testDerivedChoiceBaseArray(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testDerivedChoiceBaseArray(): Incorrect return value",equals(ret,x));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testChoiceOfChoice() throws Exception {
if (!shouldRunTest("ChoiceOfChoice")) {
return;
}
ChoiceOfChoice x=new ChoiceOfChoice();
ChoiceOfChoice yOrig=new ChoiceOfChoice();
x.setVarFloat(3.14f);
yOrig.setVarString("y456");
Holder y=new Holder(yOrig);
Holder z=new Holder();
ChoiceOfChoice ret;
if (testDocLiteral) {
ret=docClient.testChoiceOfChoice(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testChoiceOfChoice(x,y,z);
}
else {
ret=rpcClient.testChoiceOfChoice(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testChoiceOfChoice(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testChoiceOfChoice(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testChoiceOfChoice(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testGroupDirectlyInComplexType() throws Exception {
if (!shouldRunTest("GroupDirectlyInComplexType")) {
return;
}
GroupDirectlyInComplexType x=new GroupDirectlyInComplexType();
x.setVarInt(100);
x.setVarString("hello");
x.setVarFloat(1.1f);
x.setAttr1(new Integer(1));
GroupDirectlyInComplexType yOrig=new GroupDirectlyInComplexType();
yOrig.setVarInt(11);
yOrig.setVarString("world");
yOrig.setVarFloat(10.1f);
yOrig.setAttr1(new Integer(2));
Holder y=new Holder(yOrig);
Holder z=new Holder();
GroupDirectlyInComplexType ret;
if (testDocLiteral) {
ret=docClient.testGroupDirectlyInComplexType(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testGroupDirectlyInComplexType(x,y,z);
}
else {
ret=rpcClient.testGroupDirectlyInComplexType(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testGroupDirectlyInComplexType(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testGroupDirectlyInComplexType(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testGroupDirectlyInComplexType(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testDerivedStructBaseChoice() throws Exception {
if (!shouldRunTest("DerivedStructBaseChoice")) {
return;
}
DerivedStructBaseChoice x=new DerivedStructBaseChoice();
x.setVarString("BaseChoice-x");
x.setVarFloatExt(-3.14f);
x.setVarStringExt("DerivedStruct-x");
x.setAttrString("DerivedAttr-x");
DerivedStructBaseChoice yOrig=new DerivedStructBaseChoice();
yOrig.setVarFloat(-9.14f);
yOrig.setVarFloatExt(1.414f);
yOrig.setVarStringExt("DerivedStruct-y");
yOrig.setAttrString("DerivedAttr-y");
Holder y=new Holder(yOrig);
Holder z=new Holder();
DerivedStructBaseChoice ret;
if (testDocLiteral) {
ret=docClient.testDerivedStructBaseChoice(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testDerivedStructBaseChoice(x,y,z);
}
else {
ret=rpcClient.testDerivedStructBaseChoice(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testDerivedStructBaseChoice(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testDerivedStructBaseChoice(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testDerivedStructBaseChoice(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testChoiceOfSeq() throws Exception {
if (!shouldRunTest("ChoiceOfSeq")) {
return;
}
ChoiceOfSeq x=new ChoiceOfSeq();
x.setVarInt(123);
x.setVarFloat(3.14f);
ChoiceOfSeq yOrig=new ChoiceOfSeq();
yOrig.setVarOtherInt(456);
yOrig.setVarString("y456");
Holder y=new Holder(yOrig);
Holder z=new Holder();
ChoiceOfSeq ret;
if (testDocLiteral) {
ret=docClient.testChoiceOfSeq(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testChoiceOfSeq(x,y,z);
}
else {
ret=rpcClient.testChoiceOfSeq(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testChoiceOfSeq(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testChoiceOfSeq(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testChoiceOfSeq(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testDerivedChoiceBaseStruct() throws Exception {
if (!shouldRunTest("DerivedChoiceBaseStruct")) {
return;
}
DerivedChoiceBaseStruct x=new DerivedChoiceBaseStruct();
x.setVarFloat(3.14f);
x.setVarInt(new BigInteger("42"));
x.setVarString("BaseStruct-x");
x.setVarAttrString("BaseStructAttr-x");
x.setVarStringExt("DerivedChoice-x");
x.setAttrString("DerivedAttr-x");
DerivedChoiceBaseStruct yOrig=new DerivedChoiceBaseStruct();
yOrig.setVarFloat(-9.14f);
yOrig.setVarInt(new BigInteger("10"));
yOrig.setVarString("BaseStruct-y");
yOrig.setVarAttrString("BaseStructAttr-y");
yOrig.setVarFloatExt(1.414f);
yOrig.setAttrString("DerivedAttr-y");
Holder y=new Holder(yOrig);
Holder z=new Holder();
DerivedChoiceBaseStruct ret;
if (testDocLiteral) {
ret=docClient.testDerivedChoiceBaseStruct(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testDerivedChoiceBaseStruct(x,y,z);
}
else {
ret=rpcClient.testDerivedChoiceBaseStruct(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testDerivedChoiceBaseStruct(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testDerivedChoiceBaseStruct(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testDerivedChoiceBaseStruct(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testComplexTypeWithAttributes() throws Exception {
if (!shouldRunTest("ComplexTypeWithAttributes")) {
return;
}
ComplexTypeWithAttributes x=new ComplexTypeWithAttributes();
x.setAttrInt(new BigInteger("123"));
x.setAttrString("x123");
ComplexTypeWithAttributes yOrig=new ComplexTypeWithAttributes();
yOrig.setAttrInt(new BigInteger("456"));
yOrig.setAttrString("x456");
Holder y=new Holder(yOrig);
Holder z=new Holder();
ComplexTypeWithAttributes ret;
if (testDocLiteral) {
ret=docClient.testComplexTypeWithAttributes(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testComplexTypeWithAttributes(x,y,z);
}
else {
ret=rpcClient.testComplexTypeWithAttributes(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testComplexTypeWithAttributes(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testComplexTypeWithAttributes(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testComplexTypeWithAttributes(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testChoiceWithGroups() throws Exception {
if (!shouldRunTest("ChoiceWithGroups")) {
return;
}
ChoiceWithGroups x=new ChoiceWithGroups();
x.setVarInt(100);
x.setVarString("hello");
x.setVarFloat(1.1f);
ChoiceWithGroups yOrig=new ChoiceWithGroups();
yOrig.setVarOtherString("world");
Holder y=new Holder(yOrig);
Holder z=new Holder();
ChoiceWithGroups ret;
if (testDocLiteral) {
ret=docClient.testChoiceWithGroups(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testChoiceWithGroups(x,y,z);
}
else {
ret=rpcClient.testChoiceWithGroups(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testChoiceWithGroups(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testChoiceWithGroups(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testChoiceWithGroups(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testComplexTypeWithAttributeGroup1() throws Exception {
if (!shouldRunTest("ComplexTypeWithAttributeGroup1")) {
return;
}
ComplexTypeWithAttributeGroup1 x=new ComplexTypeWithAttributeGroup1();
x.setAttrInt(new BigInteger("123"));
x.setAttrString("x123");
x.setAttrFloat(new Float(3.14f));
ComplexTypeWithAttributeGroup1 yOrig=new ComplexTypeWithAttributeGroup1();
yOrig.setAttrInt(new BigInteger("456"));
yOrig.setAttrString("x456");
yOrig.setAttrFloat(new Float(6.28f));
Holder y=new Holder(yOrig);
Holder z=new Holder();
ComplexTypeWithAttributeGroup1 ret;
if (testDocLiteral) {
ret=docClient.testComplexTypeWithAttributeGroup1(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testComplexTypeWithAttributeGroup1(x,y,z);
}
else {
ret=rpcClient.testComplexTypeWithAttributeGroup1(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testComplexTypeWithAttributeGroup1(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testComplexTypeWithAttributeGroup1(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testComplexTypeWithAttributeGroup1(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testRestrictedChoiceBaseChoice() throws Exception {
if (!shouldRunTest("RestrictedChoiceBaseChoice")) {
return;
}
RestrictedChoiceBaseChoice x=new RestrictedChoiceBaseChoice();
x.setVarInt(12);
RestrictedChoiceBaseChoice yOrig=new RestrictedChoiceBaseChoice();
yOrig.setVarFloat(-9.14f);
Holder y=new Holder(yOrig);
Holder z=new Holder();
RestrictedChoiceBaseChoice ret;
if (testDocLiteral) {
ret=docClient.testRestrictedChoiceBaseChoice(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testRestrictedChoiceBaseChoice(x,y,z);
}
else {
ret=rpcClient.testRestrictedChoiceBaseChoice(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testRestrictedChoiceBaseChoice(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testRestrictedChoiceBaseChoice(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testRestrictedChoiceBaseChoice(): Incorrect return value",equals(x,ret));
}
}
BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testIDTypeAttribute() throws Exception {
if (!shouldRunTest("IDTypeAttribute")) {
return;
}
IDTypeAttribute x=new IDTypeAttribute();
x.setId("x123");
IDTypeAttribute yOrig=new IDTypeAttribute();
yOrig.setId("x456");
Holder y=new Holder(yOrig);
Holder z=new Holder();
if (testDocLiteral) {
docClient.testIDTypeAttribute(x,y,z);
}
else if (testXMLBinding) {
xmlClient.testIDTypeAttribute(x,y,z);
}
else {
rpcClient.testIDTypeAttribute(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testIDTypeAttribute(): Incorrect value for inout param",equalsIDTypeAttribute(x,y.value));
assertTrue("testIDTypeAttribute(): Incorrect value for out param",equalsIDTypeAttribute(yOrig,z.value));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testExtBase64Binary() throws Exception {
if (!shouldRunTest("ExtBase64Binary")) {
return;
}
ExtBase64Binary x1=new ExtBase64Binary();
x1.setValue("base64a".getBytes());
x1.setId(1);
ExtBase64Binary y1=new ExtBase64Binary();
y1.setValue("base64b".getBytes());
y1.setId(2);
Holder y1Holder=new Holder(y1);
Holder z1=new Holder();
ExtBase64Binary ret;
if (testDocLiteral) {
ret=docClient.testExtBase64Binary(x1,y1Holder,z1);
}
else if (testXMLBinding) {
ret=xmlClient.testExtBase64Binary(x1,y1Holder,z1);
}
else {
ret=rpcClient.testExtBase64Binary(x1,y1Holder,z1);
}
if (!perfTestOnly) {
assertTrue("testExtBase64Binary(): Incorrect value for inout param",equals(x1,y1Holder.value));
assertTrue("testExtBase64Binary(): Incorrect value for out param",equals(y1,z1.value));
assertTrue("testExtBase64Binary(): Incorrect return value",equals(x1,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testChoiceWithGroupChoice() throws Exception {
if (!shouldRunTest("ChoiceWithGroupChoice")) {
return;
}
ChoiceWithGroupChoice x=new ChoiceWithGroupChoice();
x.setVarFloat(1.1f);
ChoiceWithGroupChoice yOrig=new ChoiceWithGroupChoice();
yOrig.setVarOtherString("world");
Holder y=new Holder(yOrig);
Holder z=new Holder();
ChoiceWithGroupChoice ret;
if (testDocLiteral) {
ret=docClient.testChoiceWithGroupChoice(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testChoiceWithGroupChoice(x,y,z);
}
else {
ret=rpcClient.testChoiceWithGroupChoice(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testChoiceWithGroupChoice(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testChoiceWithGroupChoice(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testChoiceWithGroupChoice(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testChoiceWithBinary() throws Exception {
if (!shouldRunTest("ChoiceWithBinary")) {
return;
}
ChoiceWithBinary x=new ChoiceWithBinary();
x.setBase64("base64Binary_x".getBytes());
ChoiceWithBinary yOriginal=new ChoiceWithBinary();
yOriginal.setHex("hexBinary_y".getBytes());
Holder y=new Holder(yOriginal);
Holder z=new Holder();
ChoiceWithBinary ret;
if (testDocLiteral) {
ret=docClient.testChoiceWithBinary(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testChoiceWithBinary(x,y,z);
}
else {
ret=rpcClient.testChoiceWithBinary(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testChoiceWithBinary(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testChoiceWithBinary(): Incorrect value for out param",equals(yOriginal,z.value));
assertTrue("testChoiceWithBinary(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testOccuringStruct() throws Exception {
if (!shouldRunTest("OccuringStruct")) {
return;
}
OccuringStruct x=new OccuringStruct();
List theList=x.getVarFloatAndVarIntAndVarString();
theList.add(1.14f);
theList.add(new Integer(0));
theList.add("x1");
theList.add(11.14f);
theList.add(new Integer(1));
theList.add("x2");
x.setVarAttrib("x_attr");
OccuringStruct yOriginal=new OccuringStruct();
theList=yOriginal.getVarFloatAndVarIntAndVarString();
theList.add(3.14f);
theList.add(new Integer(42));
theList.add("y");
yOriginal.setVarAttrib("y_attr");
Holder y=new Holder(yOriginal);
Holder z=new Holder();
OccuringStruct ret;
if (testDocLiteral) {
ret=docClient.testOccuringStruct(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testOccuringStruct(x,y,z);
}
else {
ret=rpcClient.testOccuringStruct(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testOccuringStruct(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testOccuringStruct(): Incorrect value for out param",equals(yOriginal,z.value));
assertTrue("testOccuringStruct(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testSequenceWithGroupSeq() throws Exception {
if (!shouldRunTest("SequenceWithGroupSeq")) {
return;
}
SequenceWithGroupSeq x=new SequenceWithGroupSeq();
x.setVarInt(100);
x.setVarString("hello");
x.setVarFloat(1.1f);
x.setVarOtherInt(11);
x.setVarOtherString("world");
x.setVarOtherFloat(10.1f);
SequenceWithGroupSeq yOrig=new SequenceWithGroupSeq();
yOrig.setVarInt(11);
yOrig.setVarString("world");
yOrig.setVarFloat(10.1f);
yOrig.setVarOtherInt(100);
yOrig.setVarOtherString("hello");
yOrig.setVarOtherFloat(1.1f);
Holder y=new Holder(yOrig);
Holder z=new Holder();
SequenceWithGroupSeq ret;
if (testDocLiteral) {
ret=docClient.testSequenceWithGroupSeq(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testSequenceWithGroupSeq(x,y,z);
}
else {
ret=rpcClient.testSequenceWithGroupSeq(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testSequenceWithGroupSeq(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testSequenceWithGroupSeq(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testSequenceWithGroupSeq(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testSequenceWithGroups() throws Exception {
if (!shouldRunTest("SequenceWithGroups")) {
return;
}
SequenceWithGroups x=new SequenceWithGroups();
x.setVarInt(100);
x.setVarString("hello");
x.setVarFloat(1.1f);
x.setVarOtherFloat(1.1f);
SequenceWithGroups yOrig=new SequenceWithGroups();
yOrig.setVarInt(11);
yOrig.setVarString("world");
yOrig.setVarFloat(10.1f);
yOrig.setVarOtherString("world");
Holder y=new Holder(yOrig);
Holder z=new Holder();
SequenceWithGroups ret;
if (testDocLiteral) {
ret=docClient.testSequenceWithGroups(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testSequenceWithGroups(x,y,z);
}
else {
ret=rpcClient.testSequenceWithGroups(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testSequenceWithGroups(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testSequenceWithGroups(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testSequenceWithGroups(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testOccuringChoice2() throws Exception {
if (!shouldRunTest("OccuringChoice2")) {
return;
}
OccuringChoice2 x=new OccuringChoice2();
x.setVarString("x1");
OccuringChoice2 yOriginal=new OccuringChoice2();
yOriginal.setVarString("y1");
Holder y=new Holder(yOriginal);
Holder z=new Holder();
OccuringChoice2 ret;
if (testDocLiteral) {
ret=docClient.testOccuringChoice2(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testOccuringChoice2(x,y,z);
}
else {
ret=rpcClient.testOccuringChoice2(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testOccuringChoice2(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testOccuringChoice2(): Incorrect value for out param",equals(yOriginal,z.value));
assertTrue("testOccuringChoice2(): Incorrect return value",equals(x,ret));
}
x=new OccuringChoice2();
yOriginal=new OccuringChoice2();
yOriginal.setVarString("y1");
y=new Holder(yOriginal);
z=new Holder();
if (testDocLiteral) {
ret=docClient.testOccuringChoice2(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testOccuringChoice2(x,y,z);
}
else {
ret=rpcClient.testOccuringChoice2(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testOccuringChoice2(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testOccuringChoice2(): Incorrect value for out param",equals(yOriginal,z.value));
assertTrue("testOccuringChoice2(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testSequenceWithOccuringGroup() throws Exception {
if (!shouldRunTest("SequenceWithOccuringGroup")) {
return;
}
SequenceWithOccuringGroup x=new SequenceWithOccuringGroup();
x.getBatchElementsSeq().add(1.1f);
x.getBatchElementsSeq().add(100);
x.getBatchElementsSeq().add("hello");
SequenceWithOccuringGroup yOrig=new SequenceWithOccuringGroup();
yOrig.getBatchElementsSeq().add(2.2f);
yOrig.getBatchElementsSeq().add(200);
yOrig.getBatchElementsSeq().add("world");
Holder y=new Holder(yOrig);
Holder z=new Holder();
SequenceWithOccuringGroup ret;
if (testDocLiteral) {
ret=docClient.testSequenceWithOccuringGroup(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testSequenceWithOccuringGroup(x,y,z);
}
else {
ret=rpcClient.testSequenceWithOccuringGroup(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testGroupDirectlyInComplexType(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testGroupDirectlyInComplexType(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testGroupDirectlyInComplexType(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testDerivedNoContent() throws Exception {
if (!shouldRunTest("DerivedNoContent")) {
return;
}
DerivedNoContent x=new DerivedNoContent();
x.setVarFloat(3.14f);
x.setVarInt(new BigInteger("42"));
x.setVarString("BaseStruct-x");
x.setVarAttrString("BaseStructAttr-x");
DerivedNoContent yOrig=new DerivedNoContent();
yOrig.setVarFloat(1.414f);
yOrig.setVarInt(new BigInteger("13"));
yOrig.setVarString("BaseStruct-y");
yOrig.setVarAttrString("BaseStructAttr-y");
Holder y=new Holder(yOrig);
Holder z=new Holder();
DerivedNoContent ret;
if (testDocLiteral) {
ret=docClient.testDerivedNoContent(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testDerivedNoContent(x,y,z);
}
else {
ret=rpcClient.testDerivedNoContent(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testDerivedNoContent(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testDerivedNoContent(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testDerivedNoContent(): Incorrect return value",equals(ret,x));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testOccuringChoice1() throws Exception {
if (!shouldRunTest("OccuringChoice1")) {
return;
}
OccuringChoice1 x=new OccuringChoice1();
@SuppressWarnings("rawtypes") List theList=x.getVarFloatOrVarInt();
theList.add(0);
theList.add(new Float(1.14f));
theList.add(1);
theList.add(new Float(11.14f));
OccuringChoice1 yOriginal=new OccuringChoice1();
Holder y=new Holder(yOriginal);
Holder z=new Holder();
OccuringChoice1 ret;
if (testDocLiteral) {
ret=docClient.testOccuringChoice1(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testOccuringChoice1(x,y,z);
}
else {
ret=rpcClient.testOccuringChoice1(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testOccuringChoice1(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testOccuringChoice1(): Incorrect value for out param",equals(yOriginal,z.value));
assertTrue("testOccuringChoice1(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testChoiceWithAnyAttribute() throws Exception {
if (!shouldRunTest("ChoiceWithAnyAttribute")) {
return;
}
QName xAt1Name=new QName("http://schemas.iona.com/type_test","at_one");
QName xAt2Name=new QName("http://schemas.iona.com/type_test","at_two");
QName yAt3Name=new QName("http://apache.org/type_test","at_thr");
QName yAt4Name=new QName("http://apache.org/type_test","at_fou");
ChoiceWithAnyAttribute x=new ChoiceWithAnyAttribute();
ChoiceWithAnyAttribute y=new ChoiceWithAnyAttribute();
x.setVarString("hello");
x.setAtString("hello attribute");
x.setAtInt(new Integer(2000));
y.setVarInt(1001);
y.setAtString("there attribute");
y.setAtInt(new Integer(2002));
Map xAttrMap=x.getOtherAttributes();
xAttrMap.put(xAt1Name,"one");
xAttrMap.put(xAt2Name,"two");
Map yAttrMap=y.getOtherAttributes();
yAttrMap.put(yAt3Name,"three");
yAttrMap.put(yAt4Name,"four");
Holder yh=new Holder(y);
Holder zh=new Holder();
ChoiceWithAnyAttribute ret;
if (testDocLiteral) {
ret=docClient.testChoiceWithAnyAttribute(x,yh,zh);
}
else if (testXMLBinding) {
ret=xmlClient.testChoiceWithAnyAttribute(x,yh,zh);
}
else {
ret=rpcClient.testChoiceWithAnyAttribute(x,yh,zh);
}
if (!perfTestOnly) {
assertTrue("testChoiceWithAnyAttribute(): Incorrect value for inout param",equals(x,yh.value));
assertTrue("testChoiceWithAnyAttribute(): Incorrect value for out param",equals(y,zh.value));
assertTrue("testChoiceWithAnyAttribute(): Incorrect return value",equals(ret,x));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testMultipleOccursSequenceInSequence() throws Exception {
if (!shouldRunTest("MultipleOccursSequenceInSequence")) {
return;
}
MultipleOccursSequenceInSequence x=new MultipleOccursSequenceInSequence();
x.getValue().add(new BigInteger("32"));
MultipleOccursSequenceInSequence yOriginal=new MultipleOccursSequenceInSequence();
yOriginal.getValue().add(new BigInteger("3200"));
Holder y=new Holder(yOriginal);
Holder z=new Holder();
MultipleOccursSequenceInSequence ret;
if (testDocLiteral) {
ret=docClient.testMultipleOccursSequenceInSequence(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testMultipleOccursSequenceInSequence(x,y,z);
}
else {
ret=rpcClient.testMultipleOccursSequenceInSequence(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testMultipleOccursSequenceInSequence(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testMultipleOccursSequenceInSequence(): Incorrect value for out param",equals(yOriginal,z.value));
assertTrue("testMultipleOccursSequenceInSequence(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testOccuringChoice() throws Exception {
if (!shouldRunTest("OccuringChoice")) {
return;
}
OccuringChoice x=new OccuringChoice();
List theList=x.getVarFloatOrVarIntOrVarString();
theList.add(0);
theList.add(1.14f);
theList.add("x1");
theList.add(1);
theList.add(11.14f);
x.setVarAttrib("x_attr");
OccuringChoice yOriginal=new OccuringChoice();
theList=yOriginal.getVarFloatOrVarIntOrVarString();
theList.add(3.14f);
theList.add("y");
theList.add(42);
yOriginal.setVarAttrib("y_attr");
Holder y=new Holder(yOriginal);
Holder z=new Holder();
OccuringChoice ret;
if (testDocLiteral) {
ret=docClient.testOccuringChoice(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testOccuringChoice(x,y,z);
}
else {
ret=rpcClient.testOccuringChoice(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testOccuringChoice(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testOccuringChoice(): Incorrect value for out param",equals(yOriginal,z.value));
assertTrue("testOccuringChoice(): Incorrect return value",equals(x,ret));
}
theList.add(52);
theList.add(4.14f);
y=new Holder(yOriginal);
z=new Holder();
if (testDocLiteral) {
ret=docClient.testOccuringChoice(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testOccuringChoice(x,y,z);
}
else {
ret=rpcClient.testOccuringChoice(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testOccuringChoice(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testOccuringChoice(): Incorrect value for out param",equals(yOriginal,z.value));
assertTrue("testOccuringChoice(): Incorrect return value",equals(x,ret));
}
}
Class: org.apache.cxf.systest.type_test.AbstractTypeTestClient4 APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testRestrictedAllBaseAll() throws Exception {
if (!shouldRunTest("RestrictedAllBaseAll")) {
return;
}
RestrictedAllBaseAll x=new RestrictedAllBaseAll();
x.setVarFloat(3.14f);
x.setVarInt(42);
x.setVarAttrString("BaseAllAttr-x");
RestrictedAllBaseAll yOrig=new RestrictedAllBaseAll();
yOrig.setVarFloat(-9.14f);
yOrig.setVarInt(10);
yOrig.setVarAttrString("BaseAllAttr-y");
Holder y=new Holder(yOrig);
Holder z=new Holder();
RestrictedAllBaseAll ret;
if (testDocLiteral) {
ret=docClient.testRestrictedAllBaseAll(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testRestrictedAllBaseAll(x,y,z);
}
else {
ret=rpcClient.testRestrictedAllBaseAll(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testRestrictedAllBaseAll(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testRestrictedAllBaseAll(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testRestrictedAllBaseAll(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testOccuringChoiceWithAnyAttribute() throws Exception {
if (!shouldRunTest("OccuringChoiceWithAnyAttribute")) {
return;
}
QName xAt1Name=new QName("http://schemas.iona.com/type_test","at_one");
QName xAt2Name=new QName("http://schemas.iona.com/type_test","at_two");
QName yAt3Name=new QName("http://apache.org/type_test","at_thr");
QName yAt4Name=new QName("http://apache.org/type_test","at_fou");
OccuringChoiceWithAnyAttribute x=new OccuringChoiceWithAnyAttribute();
OccuringChoiceWithAnyAttribute y=new OccuringChoiceWithAnyAttribute();
List xVarStringOrVarInt=x.getVarStringOrVarInt();
xVarStringOrVarInt.add("hello");
xVarStringOrVarInt.add(1);
x.setAtString("attribute");
x.setAtInt(new Integer(2000));
List yVarStringOrVarInt=y.getVarStringOrVarInt();
yVarStringOrVarInt.add(1001);
y.setAtString("the attribute");
y.setAtInt(new Integer(2002));
Map xAttrMap=x.getOtherAttributes();
xAttrMap.put(xAt1Name,"one");
xAttrMap.put(xAt2Name,"two");
Map yAttrMap=y.getOtherAttributes();
yAttrMap.put(yAt3Name,"three");
yAttrMap.put(yAt4Name,"four");
Holder yh=new Holder(y);
Holder zh=new Holder();
OccuringChoiceWithAnyAttribute ret;
if (testDocLiteral) {
ret=docClient.testOccuringChoiceWithAnyAttribute(x,yh,zh);
}
else if (testXMLBinding) {
ret=xmlClient.testOccuringChoiceWithAnyAttribute(x,yh,zh);
}
else {
ret=rpcClient.testOccuringChoiceWithAnyAttribute(x,yh,zh);
}
if (!perfTestOnly) {
assertTrue("testOccuringChoiceWithAnyAttribute(): Incorrect value for inout param",equals(x,yh.value));
assertTrue("testOccuringChoiceWithAnyAttribute(): Incorrect value for out param",equals(y,zh.value));
assertTrue("testOccuringChoiceWithAnyAttribute(): Incorrect return value",equals(ret,x));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier PublicFieldVerifier
@Test public void testStructWithNillableStruct() throws Exception {
if (!shouldRunTest("StructWithNillableStruct")) {
return;
}
StructWithNillableStruct x=new StructWithNillableStruct();
x.setVarInteger(100);
x.setVarInt(101);
x.setVarFloat(101.5f);
StructWithNillableStruct yOriginal=new StructWithNillableStruct();
yOriginal.setVarInteger(200);
Holder y=new Holder(yOriginal);
Holder z=new Holder();
StructWithNillableStruct ret;
if (testDocLiteral) {
ret=docClient.testStructWithNillableStruct(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testStructWithNillableStruct(x,y,z);
}
else {
ret=rpcClient.testStructWithNillableStruct(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testStructWithNillableStruct(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testStructWithNillableStruct(): Incorrect value for out param",equals(yOriginal,z.value));
assertTrue("testStructWithNillableStruct(): Incorrect return value",equals(x,ret));
assertTrue("testStructWithNillableStruct(): Incorrect form for out param",isNormalized(z.value));
}
yOriginal.setVarInt(null);
yOriginal.setVarFloat(null);
y=new Holder(yOriginal);
z=new Holder();
if (testDocLiteral) {
ret=docClient.testStructWithNillableStruct(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testStructWithNillableStruct(x,y,z);
}
else {
ret=rpcClient.testStructWithNillableStruct(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testStructWithNillableStruct(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testStructWithNillableStruct(): Incorrect value for out param",equals(yOriginal,z.value));
assertTrue("testStructWithNillableStruct(): Incorrect return value",equals(x,ret));
assertTrue("testStructWithNillableStruct(): Incorrect form for out param",isNormalized(z.value));
}
y=new Holder(x);
x=yOriginal;
yOriginal=y.value;
z=new Holder();
if (testDocLiteral) {
ret=docClient.testStructWithNillableStruct(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testStructWithNillableStruct(x,y,z);
}
else {
ret=rpcClient.testStructWithNillableStruct(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testStructWithNillableStruct(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testStructWithNillableStruct(): Incorrect value for out param",equals(yOriginal,z.value));
assertTrue("testStructWithNillableStruct(): Incorrect return value",equals(x,ret));
assertTrue("testStructWithNillableStruct(): Incorrect form for inout param",isNormalized(y.value));
assertTrue("testStructWithNillableStruct(): Incorrect return form",isNormalized(ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testInheritanceNestedStruct() throws Exception {
if (!shouldRunTest("InheritanceNestedStruct")) {
return;
}
DerivedStructBaseStruct xs=new DerivedStructBaseStruct();
xs.setVarFloat(3.14f);
xs.setVarInt(new BigInteger("42"));
xs.setVarString("BaseStruct-x");
xs.setVarAttrString("BaseStructAttr-x");
xs.setVarFloatExt(-3.14f);
xs.setVarStringExt("DerivedStruct-x");
xs.setAttrString1("DerivedAttr1-x");
xs.setAttrString2("DerivedAttr2-x");
DerivedStructBaseStruct ys=new DerivedStructBaseStruct();
ys.setVarFloat(-9.14f);
ys.setVarInt(new BigInteger("10"));
ys.setVarString("BaseStruct-y");
ys.setVarAttrString("BaseStructAttr-y");
ys.setVarFloatExt(1.414f);
ys.setVarStringExt("DerivedStruct-y");
ys.setAttrString1("DerivedAttr1-y");
ys.setAttrString2("DerivedAttr2-y");
NestedStruct x=new NestedStruct();
x.setVarFloat(new BigDecimal("3.14"));
x.setVarInt(42);
x.setVarString("Hello There");
x.setVarEmptyStruct(new EmptyStruct());
x.setVarStruct(xs);
NestedStruct yOrig=new NestedStruct();
yOrig.setVarFloat(new BigDecimal("1.414"));
yOrig.setVarInt(13);
yOrig.setVarString("Cheerio");
yOrig.setVarEmptyStruct(new EmptyStruct());
yOrig.setVarStruct(ys);
Holder y=new Holder(yOrig);
Holder z=new Holder();
NestedStruct ret;
if (testDocLiteral) {
ret=docClient.testNestedStruct(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testNestedStruct(x,y,z);
}
else {
ret=rpcClient.testNestedStruct(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testNestedStruct(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testNestedStruct(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testNestedStruct(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testStructWithOccuringStruct() throws Exception {
if (!shouldRunTest("StructWithOccuringStruct")) {
return;
}
StructWithOccuringStruct x=new StructWithOccuringStruct();
x.setVarInteger(100);
x.getVarIntAndVarFloat().add(101);
x.getVarIntAndVarFloat().add(101.5f);
x.getVarIntAndVarFloat().add(102);
x.getVarIntAndVarFloat().add(102.5f);
StructWithOccuringStruct yOriginal=new StructWithOccuringStruct();
yOriginal.setVarInteger(200);
Holder y=new Holder(yOriginal);
Holder z=new Holder();
StructWithOccuringStruct ret;
if (testDocLiteral) {
ret=docClient.testStructWithOccuringStruct(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testStructWithOccuringStruct(x,y,z);
}
else {
ret=rpcClient.testStructWithOccuringStruct(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testStructWithOccuringStruct(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testStructWithOccuringStruct(): Incorrect value for out param",equals(yOriginal,z.value));
assertTrue("testStructWithOccuringStruct(): Incorrect return value",equals(x,ret));
assertTrue("testStructWithOccuringStruct(): Incorrect form for out param",isNormalized(z.value));
}
yOriginal.getVarIntAndVarFloat().add(201);
yOriginal.getVarIntAndVarFloat().add(202.5f);
y=new Holder(yOriginal);
z=new Holder();
if (testDocLiteral) {
ret=docClient.testStructWithOccuringStruct(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testStructWithOccuringStruct(x,y,z);
}
else {
ret=rpcClient.testStructWithOccuringStruct(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testStructWithOccuringStruct(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testStructWithOccuringStruct(): Incorrect value for out param",equals(yOriginal,z.value));
assertTrue("testStructWithOccuringStruct(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testOccuringAll() throws Exception {
if (!shouldRunTest("OccuringAll")) {
return;
}
OccuringAll x=new OccuringAll();
x.setVarInt(new Integer(42));
x.setVarAttrString("x_attr");
OccuringAll yOrig=new OccuringAll();
Holder y=new Holder(yOrig);
Holder z=new Holder();
OccuringAll ret;
if (testDocLiteral) {
ret=docClient.testOccuringAll(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testOccuringAll(x,y,z);
}
else {
ret=rpcClient.testOccuringAll(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testOccuringAll(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testOccuringAll(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testOccuringAll(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testOccuringStructWithAnyAttribute() throws Exception {
if (!shouldRunTest("OccuringStructWithAnyAttribute")) {
return;
}
QName xAt1Name=new QName("http://apache.org/type_test","at_one");
QName xAt2Name=new QName("http://apache.org/type_test","at_two");
QName yAt3Name=new QName("http://apache.org/type_test","at_thr");
QName yAt4Name=new QName("http://apache.org/type_test","at_fou");
OccuringStructWithAnyAttribute x=new OccuringStructWithAnyAttribute();
OccuringStructWithAnyAttribute y=new OccuringStructWithAnyAttribute();
List xVarStringAndVarInt=x.getVarStringAndVarInt();
xVarStringAndVarInt.add("x1");
xVarStringAndVarInt.add(0);
xVarStringAndVarInt.add("x2");
xVarStringAndVarInt.add(1);
x.setAtString("attribute");
x.setAtInt(new Integer(2000));
List yVarStringAndVarInt=y.getVarStringAndVarInt();
yVarStringAndVarInt.add("there");
yVarStringAndVarInt.add(1001);
y.setAtString("another attribute");
y.setAtInt(new Integer(2002));
Map xAttrMap=x.getOtherAttributes();
xAttrMap.put(xAt1Name,"one");
xAttrMap.put(xAt2Name,"two");
Map yAttrMap=y.getOtherAttributes();
yAttrMap.put(yAt3Name,"three");
yAttrMap.put(yAt4Name,"four");
Holder yh=new Holder(y);
Holder zh=new Holder();
OccuringStructWithAnyAttribute ret;
if (testDocLiteral) {
ret=docClient.testOccuringStructWithAnyAttribute(x,yh,zh);
}
else if (testXMLBinding) {
ret=xmlClient.testOccuringStructWithAnyAttribute(x,yh,zh);
}
else {
ret=rpcClient.testOccuringStructWithAnyAttribute(x,yh,zh);
}
if (!perfTestOnly) {
assertTrue("testOccuringStructWithAnyAttribute(): Incorrect value for inout param",equals(x,yh.value));
assertTrue("testOccuringStructWithAnyAttribute(): Incorrect value for inout param",equals(y,zh.value));
assertTrue("testOccuringStructWithAnyAttribute(): Incorrect value for inout param",equals(ret,x));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testInheritanceSimpleChoiceDerivedStruct() throws Exception {
if (!shouldRunTest("InheritanceSimpleChoiceDerivedStruct")) {
return;
}
DerivedStructBaseChoice x=new DerivedStructBaseChoice();
x.setVarString("BaseChoice-x");
x.setVarFloatExt(-3.14f);
x.setVarStringExt("DerivedStruct-x");
x.setAttrString("DerivedAttr-x");
DerivedStructBaseChoice yOrig=new DerivedStructBaseChoice();
yOrig.setVarFloat(-9.14f);
yOrig.setVarFloatExt(1.414f);
yOrig.setVarStringExt("DerivedStruct-y");
yOrig.setAttrString("DerivedAttr-y");
Holder y=new Holder(yOrig);
Holder z=new Holder();
SimpleChoice ret;
if (testDocLiteral) {
ret=docClient.testSimpleChoice(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testSimpleChoice(x,y,z);
}
else {
ret=rpcClient.testSimpleChoice(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testInheritanceSimpleChoiceDerivedStruct(): Incorrect value for inout param",equals(x,(DerivedStructBaseChoice)y.value));
assertTrue("testInheritanceSimpleChoiceDerivedStruct(): Incorrect value for out param",equals(yOrig,(DerivedStructBaseChoice)z.value));
assertTrue("testInheritanceSimpleChoiceDerivedStruct(): Incorrect return value",equals(x,(DerivedStructBaseChoice)ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testRecSeqB6918() throws Exception {
if (!shouldRunTest("RecSeqB6918")) {
return;
}
RecSeqB6918 x=new RecSeqB6918();
List theList=x.getNextSeqAndVarInt();
theList.add(new Integer(6));
theList.add(new RecSeqB6918());
theList.add(new Integer(42));
RecSeqB6918 yOrig=new RecSeqB6918();
theList=yOrig.getNextSeqAndVarInt();
theList.add(x);
theList.add(new Integer(2));
Holder y=new Holder(yOrig);
Holder z=new Holder();
RecSeqB6918 ret;
if (testDocLiteral) {
ret=docClient.testRecSeqB6918(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testRecSeqB6918(x,y,z);
}
else {
ret=rpcClient.testRecSeqB6918(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testRecSeqB6918(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testRecSeqB6918(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testRecSeqB6918(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier PublicFieldVerifier
@Test public void testStructWithNillableChoice() throws Exception {
if (!shouldRunTest("StructWithNillableChoice")) {
return;
}
StructWithNillableChoice x=new StructWithNillableChoice();
x.setVarInteger(2);
x.setVarInt(3);
StructWithNillableChoice yOriginal=new StructWithNillableChoice();
yOriginal.setVarInteger(1);
Holder y=new Holder(yOriginal);
Holder z=new Holder();
StructWithNillableChoice ret;
if (testDocLiteral) {
ret=docClient.testStructWithNillableChoice(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testStructWithNillableChoice(x,y,z);
}
else {
ret=rpcClient.testStructWithNillableChoice(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testStructWithNillableChoice(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testStructWithNillableChoice(): Incorrect value for out param",equals(yOriginal,z.value));
assertTrue("testStructWithNillableChoice(): Incorrect return value",equals(x,ret));
assertTrue("testStructWithNillableChoice(): Incorrect form for out param",isNormalized(z.value));
}
y=new Holder(x);
x=yOriginal;
yOriginal=y.value;
z=new Holder();
if (testDocLiteral) {
ret=docClient.testStructWithNillableChoice(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testStructWithNillableChoice(x,y,z);
}
else {
ret=rpcClient.testStructWithNillableChoice(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testStructWithNillableChoice(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testStructWithNillableChoice(): Incorrect value for out param",equals(yOriginal,z.value));
assertTrue("testStructWithNillableChoice(): Incorrect return value",equals(x,ret));
assertTrue("testStructWithNillableChoice(): Incorrect form for inout param",isNormalized(y.value));
assertTrue("testStructWithNillableChoice(): Incorrect return form",isNormalized(ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier PublicFieldVerifier
@Test public void testStructWithOccuringStruct2() throws Exception {
if (!shouldRunTest("StructWithOccuringStruct2")) {
return;
}
StructWithOccuringStruct x=new StructWithOccuringStruct();
x.setVarInteger(100);
x.getVarIntAndVarFloat().add(101);
x.getVarIntAndVarFloat().add(101.5f);
x.getVarIntAndVarFloat().add(102);
x.getVarIntAndVarFloat().add(102.5f);
StructWithOccuringStruct yOriginal=new StructWithOccuringStruct();
yOriginal.setVarInteger(200);
Holder y=new Holder(yOriginal);
Holder z=new Holder();
StructWithOccuringStruct ret;
y=new Holder(x);
x=yOriginal;
yOriginal=y.value;
z=new Holder();
if (testDocLiteral) {
ret=docClient.testStructWithOccuringStruct(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testStructWithOccuringStruct(x,y,z);
}
else {
ret=rpcClient.testStructWithOccuringStruct(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testStructWithOccuringStruct(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testStructWithOccuringStruct(): Incorrect value for out param",equals(yOriginal,z.value));
assertTrue("testStructWithOccuringStruct(): Incorrect return value",equals(x,ret));
}
x.getVarIntAndVarFloat().clear();
y=new Holder(yOriginal);
z=new Holder();
if (testDocLiteral) {
ret=docClient.testStructWithOccuringStruct(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testStructWithOccuringStruct(x,y,z);
}
else {
ret=rpcClient.testStructWithOccuringStruct(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testStructWithOccuringStruct(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testStructWithOccuringStruct(): Incorrect value for out param",equals(yOriginal,z.value));
assertTrue("testStructWithOccuringStruct(): Incorrect return value",equals(x,ret));
assertTrue("testStructWithOccuringStruct(): Incorrect form for inout param",isNormalized(y.value));
assertTrue("testStructWithOccuringStruct(): Incorrect return form",isNormalized(ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testInheritanceUnboundedArrayDerivedChoice() throws Exception {
if (!shouldRunTest("InheritanceUnboundedArrayDerivedChoice")) {
return;
}
DerivedChoiceBaseArray x=new DerivedChoiceBaseArray();
x.getItem().addAll(Arrays.asList("AAA","BBB","CCC"));
x.setVarStringExt("DerivedChoice-x");
x.setAttrStringExt("DerivedAttr-x");
DerivedChoiceBaseArray yOrig=new DerivedChoiceBaseArray();
yOrig.getItem().addAll(Arrays.asList("XXX","YYY","ZZZ"));
yOrig.setVarFloatExt(1.414f);
yOrig.setAttrStringExt("DerivedAttr-y");
Holder y=new Holder(yOrig);
Holder z=new Holder();
UnboundedArray ret;
if (testDocLiteral) {
ret=docClient.testUnboundedArray(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testUnboundedArray(x,y,z);
}
else {
ret=rpcClient.testUnboundedArray(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testInheritanceUnboundedArrayDerivedChoice(): Incorrect value for inout param",equals(x,(DerivedChoiceBaseArray)y.value));
assertTrue("testInheritanceUnboundedArrayDerivedChoice(): Incorrect value for out param",equals(yOrig,(DerivedChoiceBaseArray)z.value));
assertTrue("testInheritanceUnboundedArrayDerivedChoice(): Incorrect return value",equals(x,(DerivedChoiceBaseArray)ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testAnonymousType() throws Exception {
if (!shouldRunTest("AnonymousType")) {
return;
}
AnonymousType x=new AnonymousType();
AnonymousType.Foo fx=new AnonymousType.Foo();
fx.setFoo("hello");
fx.setBar("there");
x.setFoo(fx);
AnonymousType yOrig=new AnonymousType();
AnonymousType.Foo fy=new AnonymousType.Foo();
fy.setFoo("good");
fy.setBar("bye");
yOrig.setFoo(fy);
Holder y=new Holder(yOrig);
Holder z=new Holder();
AnonymousType ret;
if (testDocLiteral) {
ret=docClient.testAnonymousType(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testAnonymousType(x,y,z);
}
else {
ret=rpcClient.testAnonymousType(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testAnonymousType(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testAnonymousType(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testAnonymousType(): Incorrect return value",equals(x,ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testInheritanceSimpleStructDerivedStruct() throws Exception {
if (!shouldRunTest("InheritanceSimpleStructDerivedStruct")) {
return;
}
DerivedStructBaseStruct x=new DerivedStructBaseStruct();
x.setVarFloat(3.14f);
x.setVarInt(new BigInteger("42"));
x.setVarString("BaseStruct-x");
x.setVarAttrString("BaseStructAttr-x");
x.setVarFloatExt(-3.14f);
x.setVarStringExt("DerivedStruct-x");
x.setAttrString1("DerivedAttr1-x");
x.setAttrString2("DerivedAttr2-x");
DerivedStructBaseStruct yOrig=new DerivedStructBaseStruct();
yOrig.setVarFloat(-9.14f);
yOrig.setVarInt(new BigInteger("10"));
yOrig.setVarString("BaseStruct-y");
yOrig.setVarAttrString("BaseStructAttr-y");
yOrig.setVarFloatExt(1.414f);
yOrig.setVarStringExt("DerivedStruct-y");
yOrig.setAttrString1("DerivedAttr1-y");
yOrig.setAttrString2("DerivedAttr2-y");
Holder y=new Holder(yOrig);
Holder z=new Holder();
SimpleStruct ret;
if (testDocLiteral) {
ret=docClient.testSimpleStruct(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testSimpleStruct(x,y,z);
}
else {
ret=rpcClient.testSimpleStruct(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testInheritanceSimpleDerived(): Incorrect value for inout param",equals(x,(DerivedStructBaseStruct)y.value));
assertTrue("testInheritanceSimpleDerived(): Incorrect value for out param",equals(yOrig,(DerivedStructBaseStruct)z.value));
assertTrue("testInheritanceSimpleDerived(): Incorrect return value",equals(x,(DerivedStructBaseStruct)ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testMRecSeqA() throws Exception {
if (!shouldRunTest("MRecSeqA")) {
return;
}
MRecSeqA xA=new MRecSeqA();
MRecSeqA yA=new MRecSeqA();
MRecSeqA zA=new MRecSeqA();
MRecSeqB xB=new MRecSeqB();
MRecSeqB yB=new MRecSeqB();
xA.setVarIntA(11);
yA.setVarIntA(12);
zA.setVarIntA(13);
xB.setVarIntB(21);
yB.setVarIntB(22);
xB.setSeqA(yA);
yB.setSeqA(zA);
xA.getSeqB().add(xB);
yA.getSeqB().add(yB);
Holder yh=new Holder(yA);
Holder zh=new Holder();
MRecSeqA ret;
if (testDocLiteral) {
ret=docClient.testMRecSeqA(xA,yh,zh);
}
else if (testXMLBinding) {
ret=xmlClient.testMRecSeqA(xA,yh,zh);
}
else {
ret=rpcClient.testMRecSeqA(xA,yh,zh);
}
if (!perfTestOnly) {
assertTrue("test_MRecSeqA(): Incorrect value for inout param",equals(xA,yh.value));
assertTrue("test_MRecSeqA(): Incorrect value for out param",equals(yA,zh.value));
assertTrue("test_MRecSeqA(): Incorrect return value",equals(ret,xA));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier PublicFieldVerifier
@Test public void testStructWithOccuringChoice() throws Exception {
if (!shouldRunTest("StructWithOccuringChoice")) {
return;
}
StructWithOccuringChoice x=new StructWithOccuringChoice();
x.setVarInteger(2);
x.getVarIntOrVarString().add(3);
x.getVarIntOrVarString().add("hello");
StructWithOccuringChoice yOriginal=new StructWithOccuringChoice();
yOriginal.setVarInteger(1);
Holder y=new Holder(yOriginal);
Holder z=new Holder();
StructWithOccuringChoice ret;
if (testDocLiteral) {
ret=docClient.testStructWithOccuringChoice(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testStructWithOccuringChoice(x,y,z);
}
else {
ret=rpcClient.testStructWithOccuringChoice(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testStructWithOccuringChoice(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testStructWithOccuringChoice(): Incorrect value for out param",equals(yOriginal,z.value));
assertTrue("testStructWithOccuringChoice(): Incorrect return value",equals(x,ret));
assertTrue("testStructWithOccuringChoice(): Incorrect form for out param",isNormalized(z.value));
}
yOriginal.getVarIntOrVarString().add("world");
y=new Holder(yOriginal);
z=new Holder();
if (testDocLiteral) {
ret=docClient.testStructWithOccuringChoice(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testStructWithOccuringChoice(x,y,z);
}
else {
ret=rpcClient.testStructWithOccuringChoice(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testStructWithOccuringChoice(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testStructWithOccuringChoice(): Incorrect value for out param",equals(yOriginal,z.value));
assertTrue("testStructWithOccuringChoice(): Incorrect return value",equals(x,ret));
}
y=new Holder(x);
x=yOriginal;
yOriginal=y.value;
z=new Holder();
if (testDocLiteral) {
ret=docClient.testStructWithOccuringChoice(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testStructWithOccuringChoice(x,y,z);
}
else {
ret=rpcClient.testStructWithOccuringChoice(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testStructWithOccuringChoice(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testStructWithOccuringChoice(): Incorrect value for out param",equals(yOriginal,z.value));
assertTrue("testStructWithOccuringChoice(): Incorrect return value",equals(x,ret));
}
x.getVarIntOrVarString().clear();
y=new Holder(yOriginal);
z=new Holder();
if (testDocLiteral) {
ret=docClient.testStructWithOccuringChoice(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testStructWithOccuringChoice(x,y,z);
}
else {
ret=rpcClient.testStructWithOccuringChoice(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testStructWithOccuringChoice(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testStructWithOccuringChoice(): Incorrect value for out param",equals(yOriginal,z.value));
assertTrue("testStructWithOccuringChoice(): Incorrect return value",equals(x,ret));
assertTrue("testStructWithOccuringChoice(): Incorrect form for inout param",isNormalized(y.value));
assertTrue("testStructWithOccuringChoice(): Incorrect return form",isNormalized(ret));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testMRecSeqC() throws Exception {
if (!shouldRunTest("MRecSeqC")) {
return;
}
MRecSeqC xC=new MRecSeqC();
MRecSeqC yC=new MRecSeqC();
MRecSeqC zC=new MRecSeqC();
ArrayOfMRecSeqD xDs=new ArrayOfMRecSeqD();
ArrayOfMRecSeqD yDs=new ArrayOfMRecSeqD();
ArrayOfMRecSeqD zDs=new ArrayOfMRecSeqD();
MRecSeqD xD=new MRecSeqD();
MRecSeqD yD=new MRecSeqD();
xC.setVarIntC(11);
yC.setVarIntC(12);
zC.setVarIntC(13);
xD.setVarIntD(21);
yD.setVarIntD(22);
xDs.getSeqD().add(xD);
yDs.getSeqD().add(yD);
xC.setSeqDs(xDs);
yC.setSeqDs(yDs);
zC.setSeqDs(zDs);
xD.setSeqC(yC);
yD.setSeqC(zC);
Holder yh=new Holder(yC);
Holder zh=new Holder();
MRecSeqC ret;
if (testDocLiteral) {
ret=docClient.testMRecSeqC(xC,yh,zh);
}
else if (testXMLBinding) {
ret=xmlClient.testMRecSeqC(xC,yh,zh);
}
else {
ret=rpcClient.testMRecSeqC(xC,yh,zh);
}
if (!perfTestOnly) {
assertTrue("test_MRecSeqC(): Incorrect value for inout param",equals(xC,yh.value));
assertTrue("test_MRecSeqC(): Incorrect value for out param",equals(yC,zh.value));
assertTrue("test_MRecSeqC(): Incorrect return value",equals(ret,xC));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testSimpleContentExtWithAnyAttribute() throws Exception {
if (!shouldRunTest("SimpleContentExtWithAnyAttribute")) {
return;
}
QName xAt1Name=new QName("http://apache.org/type_test","at_one");
QName xAt2Name=new QName("http://apache.org/type_test","at_two");
QName yAt3Name=new QName("http://apache.org/type_test","at_thr");
QName yAt4Name=new QName("http://apache.org/type_test","at_fou");
SimpleContentExtWithAnyAttribute x=new SimpleContentExtWithAnyAttribute();
x.setValue("foo");
x.setAttrib(new Integer(2000));
SimpleContentExtWithAnyAttribute y=new SimpleContentExtWithAnyAttribute();
y.setValue("bar");
y.setAttrib(new Integer(2001));
Map xAttrMap=x.getOtherAttributes();
xAttrMap.put(xAt1Name,"one");
xAttrMap.put(xAt2Name,"two");
Map yAttrMap=y.getOtherAttributes();
yAttrMap.put(yAt3Name,"three");
yAttrMap.put(yAt4Name,"four");
Holder yh=new Holder(y);
Holder zh=new Holder();
SimpleContentExtWithAnyAttribute ret;
if (testDocLiteral) {
ret=docClient.testSimpleContentExtWithAnyAttribute(x,yh,zh);
}
else if (testXMLBinding) {
ret=xmlClient.testSimpleContentExtWithAnyAttribute(x,yh,zh);
}
else {
ret=rpcClient.testSimpleContentExtWithAnyAttribute(x,yh,zh);
}
if (!perfTestOnly) {
assertTrue("testSimpleContentExtWithAnyAttribute(): Incorrect value for inout param",equals(x,yh.value));
assertTrue("testSimpleContentExtWithAnyAttribute(): Incorrect value for out param",equals(y,zh.value));
assertTrue("testSimpleContentExtWithAnyAttribute(): Incorrect return value",equals(ret,x));
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testRestrictedStructBaseStruct() throws Exception {
if (!shouldRunTest("RestrictedStructBaseStruct")) {
return;
}
RestrictedStructBaseStruct x=new RestrictedStructBaseStruct();
x.setVarFloat(3.14f);
x.setVarInt(new BigInteger("42"));
x.setVarAttrString("BaseStructAttr-x");
RestrictedStructBaseStruct yOrig=new RestrictedStructBaseStruct();
yOrig.setVarFloat(-9.14f);
yOrig.setVarInt(new BigInteger("10"));
yOrig.setVarAttrString("BaseStructAttr-y");
Holder y=new Holder(yOrig);
Holder z=new Holder();
RestrictedStructBaseStruct ret;
if (testDocLiteral) {
ret=docClient.testRestrictedStructBaseStruct(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testRestrictedStructBaseStruct(x,y,z);
}
else {
ret=rpcClient.testRestrictedStructBaseStruct(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testRestrictedStructBaseStruct(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testRestrictedStructBaseStruct(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testRestrictedStructBaseStruct(): Incorrect return value",equals(x,ret));
}
}
Class: org.apache.cxf.systest.type_test.AbstractTypeTestClient5 APIUtilityVerifier BranchVerifier UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testComplexRestriction() throws Exception {
if (!shouldRunTest("ComplexRestriction")) {
return;
}
ComplexRestriction x=new ComplexRestriction();
x.setValue("str_x");
ComplexRestriction yOrig=new ComplexRestriction();
yOrig.setValue("string_yyy");
Holder y=new Holder(yOrig);
Holder z=new Holder();
ComplexRestriction ret;
if (testDocLiteral) {
ret=docClient.testComplexRestriction(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testComplexRestriction(x,y,z);
}
else {
ret=rpcClient.testComplexRestriction(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testComplexRestriction(): Incorrect value for inout param",x.getValue(),y.value.getValue());
assertEquals("testComplexRestriction(): Incorrect value for out param",yOrig.getValue(),z.value.getValue());
assertEquals("testComplexRestriction(): Incorrect return value",x.getValue(),ret.getValue());
}
if (testDocLiteral || testXMLBinding) {
try {
x=new ComplexRestriction();
x.setValue("string_x");
yOrig=new ComplexRestriction();
yOrig.setValue("string_yyyyyy");
y=new Holder(yOrig);
z=new Holder();
ret=testDocLiteral ? docClient.testComplexRestriction(x,y,z) : xmlClient.testComplexRestriction(x,y,z);
fail("maxLength=10 restriction is violated.");
}
catch ( Exception ex) {
}
}
}
APIUtilityVerifier BranchVerifier BooleanVerifier InternalCallVerifier
@Test public void testMixedArray() throws Exception {
if (!shouldRunTest("MixedArray")) {
return;
}
MixedArray x=new MixedArray();
x.getArray1().addAll(Arrays.asList("AAA","BBB","CCC"));
x.setArray2(new UnboundedArray());
x.getArray2().getItem().addAll(Arrays.asList("aaa","bbb","ccc"));
x.getArray3().addAll(Arrays.asList("DDD","EEE","FFF"));
x.setArray4(new FixedArray());
x.getArray4().getItem().addAll(Arrays.asList(1,2,3));
x.getArray5().addAll(Arrays.asList("GGG","HHH","III"));
x.setArray6(new MixedArray.Array6());
x.getArray6().getItem().addAll(Arrays.asList("ggg","hhh","iii"));
x.getArray7().addAll(Arrays.asList("JJJ","KKK","LLL"));
x.setArray8(new MixedArray.Array8());
x.getArray8().getItem().addAll(Arrays.asList(4,5,6));
Array9 array91=new MixedArray.Array9();
Array9 array92=new MixedArray.Array9();
Array9 array93=new MixedArray.Array9();
array91.setItem("MMM");
array92.setItem("NNN");
array93.setItem("OOO");
x.getArray9().addAll(Arrays.asList(array91,array92,array93));
Array10 array101=new MixedArray.Array10();
Array10 array102=new MixedArray.Array10();
Array10 array103=new MixedArray.Array10();
array101.setItem("PPP");
array102.setItem("QQQ");
array103.setItem("RRR");
x.getArray10().addAll(Arrays.asList(array101,array102,array103));
x.getArray11().addAll(Arrays.asList("AAA","BBB","CCC"));
MixedArray yOrig=new MixedArray();
yOrig.getArray1().addAll(Arrays.asList("XXX","YYY","ZZZ"));
yOrig.setArray2(new UnboundedArray());
yOrig.getArray2().getItem().addAll(Arrays.asList("xxx","yyy","zzz"));
yOrig.getArray3().addAll(Arrays.asList("DDD","EEE","FFF"));
yOrig.setArray4(new FixedArray());
yOrig.getArray4().getItem().addAll(Arrays.asList(1,2,3));
yOrig.getArray5().addAll(Arrays.asList("GGG","HHH","III"));
yOrig.setArray6(new MixedArray.Array6());
yOrig.getArray6().getItem().addAll(Arrays.asList("ggg","hhh","iii"));
yOrig.getArray7().addAll(Arrays.asList("JJJ","KKK","LLL"));
yOrig.setArray8(new MixedArray.Array8());
yOrig.getArray8().getItem().addAll(Arrays.asList(4,5,6));
array91=new MixedArray.Array9();
array92=new MixedArray.Array9();
array93=new MixedArray.Array9();
array91.setItem("MMM");
array92.setItem("NNN");
array93.setItem("OOO");
yOrig.getArray9().addAll(Arrays.asList(array91,array92,array93));
array101=new MixedArray.Array10();
array102=new MixedArray.Array10();
array103=new MixedArray.Array10();
array101.setItem("PPP");
array102.setItem("QQQ");
array103.setItem("RRR");
yOrig.getArray10().addAll(Arrays.asList(array101,array102,array103));
yOrig.getArray11().addAll(Arrays.asList("XXX","YYY","ZZZ"));
Holder y=new Holder(yOrig);
Holder z=new Holder();
MixedArray ret;
if (testDocLiteral) {
ret=docClient.testMixedArray(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testMixedArray(x,y,z);
}
else {
ret=rpcClient.testMixedArray(x,y,z);
}
if (!perfTestOnly) {
assertTrue("testMixedArray(): Incorrect value for inout param",equals(x,y.value));
assertTrue("testMixedArray(): Incorrect value for out param",equals(yOrig,z.value));
assertTrue("testMixedArray(): Incorrect return value",equals(x,ret));
}
assertEmptyCollectionsHandled(x,yOrig);
}
APIUtilityVerifier BranchVerifier UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testComplexRestriction2() throws Exception {
if (!shouldRunTest("ComplexRestriction2")) {
return;
}
ComplexRestriction2 x=new ComplexRestriction2();
x.setValue("string_xxx");
ComplexRestriction2 yOrig=new ComplexRestriction2();
yOrig.setValue("string_yyy");
Holder y=new Holder(yOrig);
Holder z=new Holder();
ComplexRestriction2 ret;
if (testDocLiteral) {
ret=docClient.testComplexRestriction2(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testComplexRestriction2(x,y,z);
}
else {
ret=rpcClient.testComplexRestriction2(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testComplexRestriction2(): Incorrect value for inout param",x.getValue(),y.value.getValue());
assertEquals("testComplexRestriction2(): Incorrect value for out param",yOrig.getValue(),z.value.getValue());
assertEquals("testComplexRestriction2(): Incorrect return value",x.getValue(),ret.getValue());
}
if (testDocLiteral || testXMLBinding) {
try {
x=new ComplexRestriction2();
x.setValue("str_x");
yOrig=new ComplexRestriction2();
yOrig.setValue("string_yyy");
y=new Holder(yOrig);
z=new Holder();
ret=testDocLiteral ? docClient.testComplexRestriction2(x,y,z) : xmlClient.testComplexRestriction2(x,y,z);
fail("length=10 restriction is violated.");
}
catch ( Exception ex) {
}
}
}
APIUtilityVerifier BranchVerifier UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testComplexRestriction4() throws Exception {
if (!shouldRunTest("ComplexRestriction4")) {
return;
}
ComplexRestriction4 x=new ComplexRestriction4();
x.setValue("str_x");
ComplexRestriction4 yOrig=new ComplexRestriction4();
yOrig.setValue("y");
Holder y=new Holder(yOrig);
Holder z=new Holder();
ComplexRestriction4 ret;
if (testDocLiteral) {
ret=docClient.testComplexRestriction4(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testComplexRestriction4(x,y,z);
}
else {
ret=rpcClient.testComplexRestriction4(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testComplexRestriction4(): Incorrect value for inout param",x.getValue(),y.value.getValue());
assertEquals("testComplexRestriction4(): Incorrect value for out param",yOrig.getValue(),z.value.getValue());
assertEquals("testComplexRestriction4(): Incorrect return value",x.getValue(),ret.getValue());
}
if (testDocLiteral || testXMLBinding) {
try {
x=new ComplexRestriction4();
x.setValue("str_xxx");
y=new Holder(yOrig);
z=new Holder();
ret=testDocLiteral ? docClient.testComplexRestriction4(x,y,z) : xmlClient.testComplexRestriction4(x,y,z);
fail("maxLength=5 restriction is violated.");
}
catch ( Exception ex) {
}
}
}
APIUtilityVerifier BranchVerifier UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testComplexRestriction3() throws Exception {
if (!shouldRunTest("ComplexRestriction3")) {
return;
}
ComplexRestriction3 x=new ComplexRestriction3();
x.setValue("str_x");
ComplexRestriction3 yOrig=new ComplexRestriction3();
yOrig.setValue("string_yyy");
Holder y=new Holder(yOrig);
Holder z=new Holder();
ComplexRestriction3 ret;
if (testDocLiteral) {
ret=docClient.testComplexRestriction3(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testComplexRestriction3(x,y,z);
}
else {
ret=rpcClient.testComplexRestriction3(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testComplexRestriction3(): Incorrect value for inout param",x.getValue(),y.value.getValue());
assertEquals("testComplexRestriction3(): Incorrect value for out param",yOrig.getValue(),z.value.getValue());
assertEquals("testComplexRestriction3(): Incorrect return value",x.getValue(),ret.getValue());
}
if (testDocLiteral || testXMLBinding) {
try {
x=new ComplexRestriction3();
x.setValue("str");
y=new Holder(yOrig);
z=new Holder();
ret=testDocLiteral ? docClient.testComplexRestriction3(x,y,z) : xmlClient.testComplexRestriction3(x,y,z);
fail("maxLength=10 && minLength=5 restriction is violated.");
}
catch ( Exception ex) {
}
try {
x=new ComplexRestriction3();
x.setValue("string_x");
yOrig=new ComplexRestriction3();
yOrig.setValue("string_yyyyyy");
y=new Holder(yOrig);
z=new Holder();
ret=testDocLiteral ? docClient.testComplexRestriction3(x,y,z) : xmlClient.testComplexRestriction3(x,y,z);
fail("maxLength=10 && minLength=5 restriction is violated.");
}
catch ( Exception ex) {
}
}
}
APIUtilityVerifier BranchVerifier UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testComplexRestriction5() throws Exception {
if (!shouldRunTest("ComplexRestriction5")) {
return;
}
ComplexRestriction5 x=new ComplexRestriction5();
x.setValue("http://www.iona.com");
ComplexRestriction5 yOrig=new ComplexRestriction5();
yOrig.setValue("http://www.iona.com/info/services/oss/");
Holder y=new Holder(yOrig);
Holder z=new Holder();
ComplexRestriction5 ret;
if (testDocLiteral) {
ret=docClient.testComplexRestriction5(x,y,z);
}
else if (testXMLBinding) {
ret=xmlClient.testComplexRestriction5(x,y,z);
}
else {
ret=rpcClient.testComplexRestriction5(x,y,z);
}
if (!perfTestOnly) {
assertEquals("testComplexRestriction5(): Incorrect value for inout param",x.getValue(),y.value.getValue());
assertEquals("testComplexRestriction5(): Incorrect value for out param",yOrig.getValue(),z.value.getValue());
assertEquals("testComplexRestriction5(): Incorrect return value",x.getValue(),ret.getValue());
}
if (testDocLiteral || testXMLBinding) {
try {
x=new ComplexRestriction5();
x.setValue("uri");
y=new Holder(yOrig);
z=new Holder();
ret=docClient.testComplexRestriction5(x,y,z);
fail("maxLength=50 && minLength=5 restriction is violated.");
}
catch ( Exception ex) {
}
try {
x=new ComplexRestriction5();
x.setValue("http://www.iona.com");
yOrig=new ComplexRestriction5();
yOrig.setValue("http://www.iona.com/info/services/oss/info_services_oss_train.html");
y=new Holder(yOrig);
z=new Holder();
ret=testDocLiteral ? docClient.testComplexRestriction5(x,y,z) : xmlClient.testComplexRestriction5(x,y,z);
fail("maxLength=50 && minLength=5 restriction is violated.");
}
catch ( Exception ex) {
}
}
}
Class: org.apache.cxf.systest.versioning.ClientServerVersioningTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testVersionBasedRouting() throws Exception {
SOAPService service=new SOAPService();
assertNotNull(service);
try {
Greeter greeter=service.getPort(portName,Greeter.class);
updateAddressPort(greeter,PORT);
GreetMe1 request=new GreetMe1();
request.setRequestType("Bonjour");
GreetMeResponse greeting=greeter.greetMe(request);
assertNotNull("no response received from service",greeting);
assertEquals("Hello Bonjour version1",greeting.getResponseType());
String reply=greeter.sayHi();
assertNotNull("no response received from service",reply);
assertEquals("Bonjour version2",reply);
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
Class: org.apache.cxf.systest.ws.addr_feature.WSAClientServerTest InternalCallVerifier EqualityVerifier
@Test public void testCxfWsaFeature() throws Exception {
ByteArrayOutputStream input=setupInLogging();
ByteArrayOutputStream output=setupOutLogging();
JaxWsProxyFactoryBean factory=new JaxWsProxyFactoryBean();
factory.setServiceClass(AddNumbersPortType.class);
factory.setAddress("http://localhost:" + PORT + "/jaxws/add");
factory.getFeatures().add(new WSAddressingFeature());
AddNumbersPortType port=(AddNumbersPortType)factory.create();
((BindingProvider)port).getRequestContext().put("ws-addressing.write.optional.replyto",Boolean.TRUE);
assertEquals(3,port.addNumbers(1,2));
assertLogContains(output.toString(),"//wsa:Address","http://www.w3.org/2005/08/addressing/anonymous");
assertLogContains(input.toString(),"//wsa:RelatesTo",getLogValue(output.toString(),"//wsa:MessageID"));
}
InternalCallVerifier EqualityVerifier
@Test public void testNoWsaFeature() throws Exception {
ByteArrayOutputStream input=setupInLogging();
ByteArrayOutputStream output=setupOutLogging();
JaxWsProxyFactoryBean factory=new JaxWsProxyFactoryBean();
factory.setServiceClass(AddNumbersPortType.class);
factory.setAddress("http://localhost:" + PORT + "/jaxws/add");
AddNumbersPortType port=(AddNumbersPortType)factory.create();
assertEquals(3,port.addNumbers(1,2));
assertLogNotContains(output.toString(),"//wsa:Address");
assertLogNotContains(input.toString(),"//wsa:RelatesTo");
}
Class: org.apache.cxf.systest.ws.addr_wsdl.WSAPureWsdlTest BranchVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testBasicInvocation() throws Exception {
ByteArrayOutputStream input=setupInLogging();
ByteArrayOutputStream output=setupOutLogging();
Response resp;
AddNumbersPortType port=getPort();
((BindingProvider)port).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"http://localhost:" + PORT + "/jaxws/add");
assertEquals(3,port.addNumbers(1,2));
String base="http://apache.org/cxf/systest/ws/addr_feature/AddNumbersPortType/";
assertLogContains(output.toString(),"//wsa:Action",base + "addNumbersRequest");
assertLogContains(input.toString(),"//wsa:Action",base + "addNumbersResponse");
resp=port.addNumbers3Async(1,2);
assertEquals(3,resp.get().getReturn());
((BindingProvider)port).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"http://localhost:" + PORT + "/doesntexist");
resp=port.addNumbers3Async(1,2);
try {
resp.get();
}
catch ( ExecutionException ex) {
assertTrue("Found " + ex.getCause().getClass(),ex.getCause() instanceof IOException);
Client c=ClientProxy.getClient(port);
for ( Interceptor extends Message> m : c.getOutInterceptors()) {
if (m instanceof MAPCodec) {
assertTrue(((MAPCodec)m).getUncorrelatedExchanges().isEmpty());
}
}
}
}
InternalCallVerifier EqualityVerifier
@Test public void testProviderEndpoint() throws Exception {
String base="http://apache.org/cxf/systest/ws/addr_feature/AddNumbersPortType/";
ByteArrayOutputStream input=setupInLogging();
ByteArrayOutputStream output=setupOutLogging();
AddNumbersPortType port=getPort();
((BindingProvider)port).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"http://localhost:" + PORT + "/jaxws/add-provider");
assertEquals(3,port.addNumbers(1,2));
assertLogContains(output.toString(),"//wsa:Action",base + "addNumbersRequest");
assertLogContains(input.toString(),"//wsa:Action",base + "addNumbersResponse");
output.reset();
input.reset();
((BindingProvider)port).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"http://localhost:" + PORT + "/jaxws/add-providernows");
assertEquals(3,port.addNumbers(1,2));
assertLogContains(output.toString(),"//wsa:Action",base + "addNumbersRequest");
assertLogContains(input.toString(),"//wsa:Action",base + "addNumbersResponse");
}
UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testBasicInvocationTimeouts() throws Exception {
AddNumbersPortType port=getPort();
((BindingProvider)port).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"http://localhost:" + PORT + "/jaxws/add");
HTTPConduit conduit=(HTTPConduit)((Client)port).getConduit();
conduit.getClient().setConnectionTimeout(25);
conduit.getClient().setReceiveTimeout(10);
try {
port.addNumbersAsync(5092,25).get();
fail("should have failed");
}
catch ( Exception t) {
assertTrue(t.getCause().toString(),t.getCause() instanceof java.net.SocketTimeoutException);
}
AsyncHandler handler=new AsyncHandler(){
public void handleResponse( Response res){
synchronized (this) {
notifyAll();
}
}
}
;
synchronized (handler) {
port.addNumbersAsync(5092,25,handler);
handler.wait(1000);
}
try {
((BindingProvider)port).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"http://localhost:" + PORT2 + "/jaxws/add");
port.addNumbersAsync(25,25).get();
fail("should have failed");
}
catch ( Exception t) {
assertTrue(t.getCause().getCause().toString(),t.getCause().getCause() instanceof java.net.ConnectException);
}
synchronized (handler) {
port.addNumbersAsync(25,25,handler);
handler.wait(1000);
}
MAPCodec mp=getMAPCodec((Client)port);
assertEquals(0,mp.getUncorrelatedExchanges().size());
}
Class: org.apache.cxf.systest.ws.addressing.MAPTestBase InternalCallVerifier EqualityVerifier
@Test public void testImplicitMAPs() throws Exception {
try {
String greeting=greeter.greetMe("implicit1");
assertEquals("unexpected response received from service","Hello implicit1",greeting);
checkVerification();
greeting=greeter.greetMe("implicit2");
assertEquals("unexpected response received from service","Hello implicit2",greeting);
checkVerification();
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
InternalCallVerifier EqualityVerifier
@Test public void testVersioning() throws Exception {
try {
mapVerifier.expectedExposedAs.add(VersionTransformer.Names200408.WSA_NAMESPACE_NAME);
mapVerifier.expectedExposedAs.add(VersionTransformer.Names200408.WSA_NAMESPACE_NAME);
String greeting=greeter.greetMe("versioning1");
assertEquals("unexpected response received from service","Hello versioning1",greeting);
checkVerification();
greeting=greeter.greetMe("versioning2");
assertEquals("unexpected response received from service","Hello versioning2",greeting);
checkVerification();
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testApplicationFault() throws Exception {
try {
greeter.testDocLitFault("BadRecordLitFault");
fail("expected fault from service");
}
catch ( BadRecordLitFault brlf) {
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
String greeting=greeter.greetMe("intra-fault");
assertEquals("unexpected response received from service","Hello intra-fault",greeting);
try {
greeter.testDocLitFault("NoSuchCodeLitFault");
fail("expected NoSuchCodeLitFault");
}
catch ( NoSuchCodeLitFault nsclf) {
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testExplicitMAPs() throws Exception {
try {
String msgId="urn:uuid:12345-" + Math.random();
Map requestContext=((BindingProvider)greeter).getRequestContext();
AddressingProperties maps=new AddressingProperties();
AttributedURIType id=ContextUtils.getAttributedURI(msgId);
maps.setMessageID(id);
requestContext.put(CLIENT_ADDRESSING_PROPERTIES,maps);
String greeting=greeter.greetMe("explicit1");
assertEquals("unexpected response received from service","Hello explicit1",greeting);
checkVerification();
try {
greeter.greetMe("explicit2");
fail("expected ProtocolException on duplicate message ID");
}
catch ( ProtocolException pe) {
assertEquals("expected duplicate message ID failure","Duplicate Message ID " + msgId,pe.getMessage());
checkVerification();
}
maps.setMessageID(null);
greeting=greeter.greetMe("explicit3");
assertEquals("unexpected response received from service","Hello explicit3",greeting);
}
catch ( UndeclaredThrowableException ex) {
throw (Exception)ex.getCause();
}
}
Class: org.apache.cxf.systest.ws.mex.MEXTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGet(){
JaxWsProxyFactoryBean proxyFac=new JaxWsProxyFactoryBean();
proxyFac.setBus(getStaticBus());
proxyFac.setAddress("http://localhost:" + PORT + "/jaxws/addmex");
proxyFac.getFeatures().add(new LoggingFeature());
MetadataExchange exc=proxyFac.create(MetadataExchange.class);
Metadata metadata=exc.get2004();
assertNotNull(metadata);
assertEquals(2,metadata.getMetadataSection().size());
assertEquals("http://schemas.xmlsoap.org/wsdl/",metadata.getMetadataSection().get(0).getDialect());
assertEquals("http://apache.org/cxf/systest/ws/addr_feature/",metadata.getMetadataSection().get(0).getIdentifier());
assertEquals("http://www.w3.org/2001/XMLSchema",metadata.getMetadataSection().get(1).getDialect());
GetMetadata body=new GetMetadata();
body.setDialect("http://www.w3.org/2001/XMLSchema");
metadata=exc.getMetadata(body);
assertEquals(1,metadata.getMetadataSection().size());
assertEquals("http://www.w3.org/2001/XMLSchema",metadata.getMetadataSection().get(0).getDialect());
}
Class: org.apache.cxf.systest.ws.policy.AddressingAnonymousPolicyTest UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testUsingAddressing() throws Exception {
SpringBusFactory bf=new SpringBusFactory();
bus=bf.createBus("org/apache/cxf/systest/ws/policy/addr-anon-client.xml");
BusFactory.setDefaultBus(bus);
LoggingInInterceptor in=new LoggingInInterceptor();
bus.getInInterceptors().add(in);
bus.getInFaultInterceptors().add(in);
LoggingOutInterceptor out=new LoggingOutInterceptor();
bus.getOutInterceptors().add(out);
bus.getOutFaultInterceptors().add(out);
BasicGreeterService gs=new BasicGreeterService();
final Greeter greeter=gs.getGreeterPort();
updateAddressPort(greeter,PORT);
LOG.fine("Created greeter client.");
ConnectionHelper.setKeepAliveConnection(greeter,true);
greeter.greetMeOneWay("CXF");
assertEquals("CXF",greeter.greetMe("cxf"));
try {
greeter.pingMe();
}
catch ( PingMeFault ex) {
fail("First invocation should have succeeded.");
}
try {
greeter.pingMe();
fail("Expected PingMeFault not thrown.");
}
catch ( PingMeFault ex) {
assertEquals(2,ex.getFaultInfo().getMajor());
assertEquals(1,ex.getFaultInfo().getMinor());
}
((Closeable)greeter).close();
}
Class: org.apache.cxf.systest.ws.policy.AddressingInlinePolicyTest UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testUsingAddressing() throws Exception {
SpringBusFactory bf=new SpringBusFactory();
bus=bf.createBus("org/apache/cxf/systest/ws/policy/addr-inline-policy-old.xml");
BusFactory.setDefaultBus(bus);
BasicGreeterService gs=new BasicGreeterService();
final Greeter greeter=gs.getGreeterPort();
updateAddressPort(greeter,PORT);
LOG.fine("Created greeter client.");
ConnectionHelper.setKeepAliveConnection(greeter,true);
testInterceptors(bus);
greeter.greetMeOneWay("CXF");
assertEquals("CXF",greeter.greetMe("cxf"));
try {
greeter.pingMe();
}
catch ( PingMeFault ex) {
fail("First invocation should have succeeded.");
}
try {
greeter.pingMe();
fail("Expected PingMeFault not thrown.");
}
catch ( PingMeFault ex) {
assertEquals(2,ex.getFaultInfo().getMajor());
assertEquals(1,ex.getFaultInfo().getMinor());
}
((Closeable)greeter).close();
}
Class: org.apache.cxf.systest.ws.policy.AddressingOptionalPolicyTest UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testNotUsingAddressing() throws Exception {
SpringBusFactory bf=new SpringBusFactory();
bus=bf.createBus("org/apache/cxf/systest/ws/policy/addr-optional.xml");
BusFactory.setDefaultBus(bus);
InMessageRecorder in=new InMessageRecorder();
bus.getInInterceptors().add(in);
OutMessageRecorder out=new OutMessageRecorder();
bus.getOutInterceptors().add(out);
bus.getExtension(PolicyEngine.class).setAlternativeSelector(new MinimalAlternativeSelector());
BasicGreeterService gs=new BasicGreeterService();
final Greeter greeter=gs.getGreeterPort();
updateAddressPort(greeter,PORT);
LOG.fine("Created greeter client.");
ConnectionHelper.setKeepAliveConnection(greeter,true);
greeter.greetMeOneWay("CXF");
assertEquals("CXF",greeter.greetMe("cxf"));
try {
greeter.pingMe();
}
catch ( PingMeFault ex) {
fail("First invocation should have succeeded.");
}
try {
greeter.pingMe();
fail("Expected PingMeFault not thrown.");
}
catch ( PingMeFault ex) {
assertEquals(2,ex.getFaultInfo().getMajor());
assertEquals(1,ex.getFaultInfo().getMinor());
}
MessageFlow mf=new MessageFlow(out.getOutboundMessages(),in.getInboundMessages());
for (int i=0; i < 3; i++) {
mf.verifyNoHeader(RMUtils.getAddressingConstants().getMessageIDQName(),true,i);
mf.verifyNoHeader(RMUtils.getAddressingConstants().getMessageIDQName(),false,i);
}
((Closeable)greeter).close();
}
UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testUsingAddressing() throws Exception {
SpringBusFactory bf=new SpringBusFactory();
bus=bf.createBus("org/apache/cxf/systest/ws/policy/addr-optional.xml");
BusFactory.setDefaultBus(bus);
InMessageRecorder in=new InMessageRecorder();
bus.getInInterceptors().add(in);
OutMessageRecorder out=new OutMessageRecorder();
bus.getOutInterceptors().add(out);
BasicGreeterService gs=new BasicGreeterService();
final Greeter greeter=gs.getGreeterPort();
updateAddressPort(greeter,PORT);
LOG.fine("Created greeter client.");
ConnectionHelper.setKeepAliveConnection(greeter,true);
greeter.greetMeOneWay("CXF");
assertEquals("CXF",greeter.greetMe("cxf"));
try {
greeter.pingMe();
}
catch ( PingMeFault ex) {
fail("First invocation should have succeeded.");
}
try {
greeter.pingMe();
fail("Expected PingMeFault not thrown.");
}
catch ( PingMeFault ex) {
assertEquals(2,ex.getFaultInfo().getMajor());
assertEquals(1,ex.getFaultInfo().getMinor());
}
MessageFlow mf=new MessageFlow(out.getOutboundMessages(),in.getInboundMessages());
for (int i=0; i < 3; i++) {
mf.verifyHeader(RMUtils.getAddressingConstants().getMessageIDQName(),true,i);
mf.verifyHeader(RMUtils.getAddressingConstants().getMessageIDQName(),false,i);
}
((Closeable)greeter).close();
}
Class: org.apache.cxf.systest.ws.policy.AddressingPolicy0705Test UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testUsingAddressing() throws Exception {
SpringBusFactory bf=new SpringBusFactory();
bus=bf.createBus("org/apache/cxf/systest/ws/policy/addr0705.xml");
BusFactory.setDefaultBus(bus);
LoggingInInterceptor in=new LoggingInInterceptor();
bus.getInInterceptors().add(in);
bus.getInFaultInterceptors().add(in);
LoggingOutInterceptor out=new LoggingOutInterceptor();
bus.getOutInterceptors().add(out);
bus.getOutFaultInterceptors().add(out);
BasicGreeterService gs=new BasicGreeterService();
final Greeter greeter=gs.getGreeterPort();
updateAddressPort(greeter,PORT);
LOG.fine("Created greeter client.");
ConnectionHelper.setKeepAliveConnection(greeter,true);
assertEquals("CXF",greeter.greetMe("cxf"));
try {
greeter.pingMe();
}
catch ( PingMeFault ex) {
fail("First invocation should have succeeded.");
}
try {
greeter.pingMe();
fail("Expected PingMeFault not thrown.");
}
catch ( PingMeFault ex) {
assertEquals(2,ex.getFaultInfo().getMajor());
assertEquals(1,ex.getFaultInfo().getMinor());
}
((Closeable)greeter).close();
}
Class: org.apache.cxf.systest.ws.policy.AddressingPolicyExternalAttachmentWsdl11Test InternalCallVerifier EqualityVerifier
@Test public void testUsingAddressing() throws Exception {
SpringBusFactory bf=new SpringBusFactory();
bus=bf.createBus("org/apache/cxf/systest/ws/policy/addr-wsdl11.xml");
BusFactory.setDefaultBus(bus);
LoggingInInterceptor in=new LoggingInInterceptor();
bus.getInInterceptors().add(in);
bus.getInFaultInterceptors().add(in);
LoggingOutInterceptor out=new LoggingOutInterceptor();
bus.getOutInterceptors().add(out);
bus.getOutFaultInterceptors().add(out);
BasicGreeterService gs=new BasicGreeterService();
final Greeter greeter=gs.getGreeterPort();
updateAddressPort(greeter,PORT);
LOG.fine("Created greeter client.");
ConnectionHelper.setKeepAliveConnection(greeter,true);
assertEquals("CXF",greeter.greetMe("cxf"));
((Closeable)greeter).close();
}
Class: org.apache.cxf.systest.ws.policy.AddressingPolicyTest UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testUsingAddressing() throws Exception {
SpringBusFactory bf=new SpringBusFactory();
bus=bf.createBus("org/apache/cxf/systest/ws/policy/addr.xml");
BusFactory.setDefaultBus(bus);
LoggingInInterceptor in=new LoggingInInterceptor();
bus.getInInterceptors().add(in);
bus.getInFaultInterceptors().add(in);
LoggingOutInterceptor out=new LoggingOutInterceptor();
bus.getOutInterceptors().add(out);
bus.getOutFaultInterceptors().add(out);
BasicGreeterService gs=new BasicGreeterService();
final Greeter greeter=gs.getGreeterPort();
updateAddressPort(greeter,PORT);
LOG.fine("Created greeter client.");
ConnectionHelper.setKeepAliveConnection(greeter,true);
assertEquals("CXF",greeter.greetMe("cxf"));
try {
greeter.pingMe();
}
catch ( PingMeFault ex) {
fail("First invocation should have succeeded.");
}
try {
greeter.pingMe();
fail("Expected PingMeFault not thrown.");
}
catch ( PingMeFault ex) {
assertEquals(2,ex.getFaultInfo().getMajor());
assertEquals(1,ex.getFaultInfo().getMinor());
}
((Closeable)greeter).close();
}
Class: org.apache.cxf.systest.ws.policy.HTTPClientPolicyTest APIUtilityVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testUsingHTTPClientPolicies() throws Exception {
SpringBusFactory bf=new SpringBusFactory();
bus=bf.createBus(POLICY_ENGINE_ENABLED_CFG);
BusFactory.setDefaultBus(bus);
LoggingInInterceptor in=new LoggingInInterceptor();
bus.getInInterceptors().add(in);
bus.getInFaultInterceptors().add(in);
LoggingOutInterceptor out=new LoggingOutInterceptor();
bus.getOutInterceptors().add(out);
bus.getOutFaultInterceptors().add(out);
URL url=HTTPClientPolicyTest.class.getResource("http_client_greeter.wsdl");
BasicGreeterService gs=new BasicGreeterService(url,GREETER_QNAME);
final Greeter greeter=gs.getGreeterPort();
updateAddressPort(greeter,PORT);
LOG.fine("Created greeter client.");
try {
greeter.sayHi();
fail("Did not receive expected PolicyException.");
}
catch ( WebServiceException wex) {
PolicyException ex=(PolicyException)wex.getCause();
assertEquals("INCOMPATIBLE_HTTPCLIENTPOLICY_ASSERTIONS",ex.getCode());
}
greeter.greetMeOneWay("CXF");
assertEquals("CXF",greeter.greetMe("cxf"));
try {
greeter.greetMe("cxf");
fail("Didn't get the exception");
}
catch ( Exception ex) {
assertTrue(ex.getCause().getClass().getName(),ex.getCause() instanceof SocketTimeoutException);
}
try {
greeter.pingMe();
fail("Expected PingMeFault not thrown.");
}
catch ( PingMeFault ex) {
assertEquals(2,ex.getFaultInfo().getMajor());
assertEquals(1,ex.getFaultInfo().getMinor());
}
((Closeable)greeter).close();
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testHTTPClientPolicyViaFeature() throws Exception {
SpringBusFactory bf=new SpringBusFactory();
bus=bf.createBus(POLICY_VIA_FEATURE_CFG);
BusFactory.setDefaultBus(bus);
URL url=HTTPClientPolicyTest.class.getResource("bare_greeter.wsdl");
BasicGreeterService gs=new BasicGreeterService(url,GREETER_QNAME);
final Greeter greeter=gs.getGreeterPort();
LOG.fine("Created greeter client.");
updateAddressPort(greeter,PORT);
greeter.greetMeOneWay("CXF");
HTTPConduit c=(HTTPConduit)(ClientProxy.getClient(greeter).getConduit());
assertNotNull("expected HTTPConduit",c);
assertNotNull("expected DecoupledEndpoint",c.getClient().getDecoupledEndpoint());
assertEquals("unexpected DecoupledEndpoint","http://localhost:9909/decoupled_endpoint",c.getClient().getDecoupledEndpoint());
((Closeable)greeter).close();
}
Class: org.apache.cxf.systest.ws.policy.HTTPServerPolicyTest APIUtilityVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testUsingHTTPServerPolicies() throws Exception {
SpringBusFactory bf=new SpringBusFactory();
Bus bus=bf.createBus();
BasicGreeterService gs=new BasicGreeterService();
final Greeter greeter=gs.getGreeterPort();
updateAddressPort(greeter,PORT);
LoggingInInterceptor in=new LoggingInInterceptor();
LoggingOutInterceptor out=new LoggingOutInterceptor();
bus.getInInterceptors().add(in);
bus.getOutInterceptors().add(out);
LOG.fine("Created greeter client.");
try {
greeter.sayHi();
fail("Did not receive expected Exception.");
}
catch ( WebServiceException wse) {
SoapFault sf=(SoapFault)wse.getCause();
assertEquals("Server",sf.getFaultCode().getLocalPart());
String text=sf.getMessage();
assertTrue(text.contains("{http://cxf.apache.org/transports/http/configuration}server"));
}
assertEquals("CXF",greeter.greetMe("cxf"));
try {
greeter.pingMe();
fail("Expected PingMeFault not thrown.");
}
catch ( PingMeFault ex) {
assertEquals(2,ex.getFaultInfo().getMajor());
assertEquals(1,ex.getFaultInfo().getMinor());
}
((Closeable)greeter).close();
}
Class: org.apache.cxf.systest.ws.policy.NestedAddressingPolicyTest InternalCallVerifier EqualityVerifier
@Test public void greetMeWSA() throws Exception {
SpringBusFactory bf=new SpringBusFactory();
bus=bf.createBus();
BusFactory.setDefaultBus(bus);
BasicGreeterService gs=new BasicGreeterService();
final Greeter greeter=gs.getGreeterPort();
updateAddressPort(greeter,PORT);
LoggingInInterceptor in=new LoggingInInterceptor();
LoggingOutInterceptor out=new LoggingOutInterceptor();
MAPCodec mapCodec=new MAPCodec();
MAPAggregatorImpl mapAggregator=new MAPAggregatorImpl();
bus.getInInterceptors().add(in);
bus.getInInterceptors().add(mapCodec);
bus.getInInterceptors().add(mapAggregator);
bus.getOutInterceptors().add(out);
bus.getOutInterceptors().add(mapCodec);
bus.getOutInterceptors().add(mapAggregator);
String s=greeter.greetMe("mytest");
assertEquals("MYTEST",s);
((Closeable)greeter).close();
}
Class: org.apache.cxf.systest.ws.policy.RM10PolicyWsdlTest UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testUsingRM() throws Exception {
setUpBus(PORT);
ReliableGreeterService gs=new ReliableGreeterService();
Greeter greeter=gs.getGreeterPort();
updateAddressPort(greeter,PORT);
LOG.fine("Created greeter client.");
ConnectionHelper.setKeepAliveConnection(greeter,true);
assertEquals("CXF",greeter.greetMe("cxf"));
greeter.greetMeOneWay("CXF");
try {
greeter.pingMe();
}
catch ( PingMeFault ex) {
fail("First invocation should have succeeded.");
}
try {
greeter.pingMe();
fail("Expected PingMeFault not thrown.");
}
catch ( PingMeFault ex) {
assertEquals(2,ex.getFaultInfo().getMajor());
assertEquals(1,ex.getFaultInfo().getMinor());
}
MessageRecorder mr=new MessageRecorder(outRecorder,inRecorder);
mr.awaitMessages(5,4,5000);
MessageFlow mf=new MessageFlow(outRecorder.getOutboundMessages(),inRecorder.getInboundMessages(),"http://schemas.xmlsoap.org/ws/2004/08/addressing","http://schemas.xmlsoap.org/ws/2005/02/rm");
mf.verifyMessages(5,true);
String[] expectedActions=new String[]{RM10Constants.INSTANCE.getCreateSequenceAction(),GREETME_ACTION,GREETMEONEWAY_ACTION,PINGME_ACTION,PINGME_ACTION};
mf.verifyActions(expectedActions,true);
mf.verifyMessageNumbers(new String[]{null,"1","2","3","4"},true);
mf.verifyLastMessage(new boolean[]{false,false,false,false,false},true);
mf.verifyAcknowledgements(new boolean[]{false,false,true,false,true},true);
mf.verifyMessages(4,false);
expectedActions=new String[]{RM10Constants.INSTANCE.getCreateSequenceResponseAction(),GREETME_RESPONSE_ACTION,PINGME_RESPONSE_ACTION,GREETER_FAULT_ACTION};
mf.verifyActions(expectedActions,false);
mf.verifyMessageNumbers(new String[]{null,"1","2","3"},false);
mf.verifyLastMessage(new boolean[]{false,false,false,false},false);
mf.verifyAcknowledgements(new boolean[]{false,true,true,true},false);
((Closeable)greeter).close();
}
Class: org.apache.cxf.systest.ws.policy.RM12PolicyWsdlTest UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testUsingRM12() throws Exception {
setUpBus(PORT);
Reliable12GreeterService gs=new Reliable12GreeterService();
Greeter greeter=gs.getGreeterPort();
updateAddressPort(greeter,PORT);
ConnectionHelper.setKeepAliveConnection(greeter,true);
LOG.fine("Created greeter client.");
assertEquals("CXF",greeter.greetMe("cxf"));
greeter.greetMeOneWay("CXF");
try {
greeter.pingMe();
}
catch ( PingMeFault ex) {
fail("First invocation should have succeeded.");
}
try {
greeter.pingMe();
fail("Expected PingMeFault not thrown.");
}
catch ( PingMeFault ex) {
assertEquals(2,ex.getFaultInfo().getMajor());
assertEquals(1,ex.getFaultInfo().getMinor());
}
MessageRecorder mr=new MessageRecorder(outRecorder,inRecorder);
mr.awaitMessages(5,4,5000);
MessageFlow mf=new MessageFlow(outRecorder.getOutboundMessages(),inRecorder.getInboundMessages(),"http://www.w3.org/2005/08/addressing","http://docs.oasis-open.org/ws-rx/wsrm/200702");
mf.verifyMessages(5,true);
String[] expectedActions=new String[]{RM11Constants.INSTANCE.getCreateSequenceAction(),GREETME_ACTION,GREETMEONEWAY_ACTION,PINGME_ACTION,PINGME_ACTION};
mf.verifyActions(expectedActions,true);
mf.verifyMessageNumbers(new String[]{null,"1","2","3","4"},true);
mf.verifyLastMessage(new boolean[]{false,false,false,false,false},true);
mf.verifyAcknowledgements(new boolean[]{false,false,true,false,true},true);
mf.verifyMessages(4,false);
expectedActions=new String[]{RM11Constants.INSTANCE.getCreateSequenceResponseAction(),GREETME_RESPONSE_ACTION,PINGME_RESPONSE_ACTION,GREETER_FAULT_ACTION};
mf.verifyActions(expectedActions,false);
mf.verifyMessageNumbers(new String[]{null,"1","2","3"},false);
mf.verifyLastMessage(new boolean[]{false,false,false,false},false);
mf.verifyAcknowledgements(new boolean[]{false,true,true,true},false);
((Closeable)greeter).close();
}
Class: org.apache.cxf.systest.ws.policy.RMPolicyTest UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testUsingRM() throws Exception {
SpringBusFactory bf=new SpringBusFactory();
bus=bf.createBus("org/apache/cxf/systest/ws/policy/rm.xml");
BusFactory.setDefaultBus(bus);
OutMessageRecorder outRecorder=new OutMessageRecorder();
bus.getOutInterceptors().add(outRecorder);
InMessageRecorder inRecorder=new InMessageRecorder();
bus.getInInterceptors().add(inRecorder);
BasicGreeterService gs=new BasicGreeterService();
final Greeter greeter=gs.getGreeterPort();
updateAddressPort(greeter,PORT);
LOG.fine("Created greeter client.");
ConnectionHelper.setKeepAliveConnection(greeter,true);
assertEquals("CXF",greeter.greetMe("cxf"));
greeter.greetMeOneWay("CXF");
try {
greeter.pingMe();
}
catch ( PingMeFault ex) {
fail("First invocation should have succeeded.");
}
try {
greeter.pingMe();
fail("Expected PingMeFault not thrown.");
}
catch ( PingMeFault ex) {
assertEquals(2,ex.getFaultInfo().getMajor());
assertEquals(1,ex.getFaultInfo().getMinor());
}
MessageRecorder mr=new MessageRecorder(outRecorder,inRecorder);
mr.awaitMessages(5,4,5000);
MessageFlow mf=new MessageFlow(outRecorder.getOutboundMessages(),inRecorder.getInboundMessages(),Names200408.WSA_NAMESPACE_NAME,RM10Constants.NAMESPACE_URI);
mf.verifyMessages(5,true);
String[] expectedActions=new String[]{RM10Constants.INSTANCE.getCreateSequenceAction(),GREETME_ACTION,GREETMEONEWAY_ACTION,PINGME_ACTION,PINGME_ACTION};
mf.verifyActions(expectedActions,true);
mf.verifyMessageNumbers(new String[]{null,"1","2","3","4"},true);
mf.verifyLastMessage(new boolean[]{false,false,false,false,false},true);
mf.verifyAcknowledgements(new boolean[]{false,false,true,false,true},true);
mf.verifyMessages(4,false);
expectedActions=new String[]{RM10Constants.INSTANCE.getCreateSequenceResponseAction(),GREETME_RESPONSE_ACTION,PINGME_RESPONSE_ACTION,GREETER_FAULT_ACTION};
mf.verifyActions(expectedActions,false);
mf.verifyMessageNumbers(new String[]{null,"1","2","3"},false);
mf.verifyLastMessage(new boolean[]{false,false,false,false},false);
mf.verifyAcknowledgements(new boolean[]{false,true,true,true},false);
((Closeable)greeter).close();
}
Class: org.apache.cxf.systest.ws.rm.AbstractServerPersistenceTest BooleanVerifier InternalCallVerifier
@Test public void testRecovery() throws Exception {
SpringBusFactory bf=new SpringBusFactory();
bus=bf.createBus();
BusFactory.setDefaultBus(bus);
LOG.fine("Created bus " + bus + " with default cfg");
ControlService cs=new ControlService();
Control control=cs.getControlPort();
ConnectionHelper.setKeepAliveConnection(control,false,true);
updateAddressPort(control,getPort());
assertTrue("Failed to start greeter",control.startGreeter(SERVER_LOSS_CFG));
LOG.fine("Started greeter server.");
System.setProperty("db.name",getPrefix() + "-recovery");
greeterBus=new SpringBusFactory().createBus(CFG);
System.clearProperty("db.name");
LOG.fine("Created bus " + greeterBus + " with cfg : "+ CFG);
BusFactory.setDefaultBus(greeterBus);
greeterBus.getExtension(RMManager.class).getConfiguration().setBaseRetransmissionInterval(new Long(60000));
GreeterService gs=new GreeterService();
Greeter greeter=gs.getGreeterPort();
updateAddressPort(greeter,getPort());
LOG.fine("Created greeter client.");
ConnectionHelper.setKeepAliveConnection(greeter,false,true);
Client c=ClientProxy.getClient(greeter);
HTTPConduit hc=(HTTPConduit)(c.getConduit());
HTTPClientPolicy cp=hc.getClient();
cp.setDecoupledEndpoint("http://localhost:" + getDecoupledPort() + "/decoupled_endpoint");
out=new OutMessageRecorder();
in=new InMessageRecorder();
greeterBus.getOutInterceptors().add(out);
greeterBus.getInInterceptors().add(in);
LOG.fine("Configured greeter client.");
Response responses[]=cast(new Response[4]);
responses[0]=greeter.greetMeAsync("one");
responses[1]=greeter.greetMeAsync("two");
responses[2]=greeter.greetMeAsync("three");
verifyMissingResponse(responses);
control.stopGreeter(SERVER_LOSS_CFG);
LOG.fine("Stopped greeter server");
out.getOutboundMessages().clear();
in.getInboundMessages().clear();
control.startGreeter(CFG);
String nl=System.getProperty("line.separator");
LOG.fine("Restarted greeter server" + nl + nl);
verifyServerRecovery(responses);
responses[3]=greeter.greetMeAsync("four");
verifyRetransmissionQueue();
verifyAcknowledgementRange(1,4);
out.getOutboundMessages().clear();
in.getInboundMessages().clear();
greeterBus.shutdown(true);
control.stopGreeter(CFG);
bus.shutdown(true);
}
Class: org.apache.cxf.systest.ws.rm.CachedOutMessageTest BooleanVerifier InternalCallVerifier
@Test public void testCachedOutMessage() throws Exception {
SpringBusFactory bf=new SpringBusFactory();
bus=bf.createBus("/org/apache/cxf/systest/ws/rm/message-loss.xml");
BusFactory.setDefaultBus(bus);
LoggingInInterceptor in=new LoggingInInterceptor();
bus.getInInterceptors().add(in);
bus.getInFaultInterceptors().add(in);
LoggingOutInterceptor out=new LoggingOutInterceptor();
bus.getOutInterceptors().add(out);
MessageLossSimulator mls=new MessageLossSimulator();
bus.getOutInterceptors().add(mls);
RMManager manager=bus.getExtension(RMManager.class);
manager.getConfiguration().setBaseRetransmissionInterval(new Long(2000));
bus.getOutFaultInterceptors().add(out);
GreeterService gs=new GreeterService();
final Greeter greeter=gs.getGreeterPort();
updateAddressPort(greeter,PORT);
LOG.fine("Created greeter client.");
ConnectionHelper.setKeepAliveConnection(greeter,true);
greeter.greetMeOneWay("one");
greeter.greetMeOneWay("two");
greeter.greetMeOneWay("three");
long wait=4000;
while (wait > 0) {
long start=System.currentTimeMillis();
try {
Thread.sleep(wait);
}
catch ( InterruptedException ex) {
}
wait-=System.currentTimeMillis() - start;
}
boolean empty=manager.getRetransmissionQueue().isEmpty();
assertTrue("Some messages are not acknowledged",empty);
}
Class: org.apache.cxf.systest.ws.rm.DecoupledBareTest BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testDecoupled() throws Exception {
SpringBusFactory bf=new SpringBusFactory();
bus=bf.createBus("/org/apache/cxf/systest/ws/rm/decoupled_bare.xml");
BusFactory.setDefaultBus(bus);
SOAPServiceAddressingDocLitBare service=new SOAPServiceAddressingDocLitBare();
assertNotNull(service);
DocLitBare greeter=service.getSoapPort();
updateAddressPort(greeter,PORT);
((BindingProvider)greeter).getRequestContext().put(Message.SCHEMA_VALIDATION_ENABLED,Boolean.TRUE);
ConnectionHelper.setKeepAliveConnection(greeter,true);
BareDocumentResponse bareres=greeter.testDocLitBare("MySimpleDocument");
assertNotNull("no response for operation testDocLitBare",bareres);
assertEquals("CXF",bareres.getCompany());
assertTrue(bareres.getId() == 1);
}
Class: org.apache.cxf.systest.ws.rm.DecoupledClientServerTest InternalCallVerifier EqualityVerifier
@Test public void testDecoupled() throws Exception {
SpringBusFactory bf=new SpringBusFactory();
bus=bf.createBus("/org/apache/cxf/systest/ws/rm/decoupled.xml");
BusFactory.setDefaultBus(bus);
LoggingInInterceptor in=new LoggingInInterceptor();
bus.getInInterceptors().add(in);
bus.getInFaultInterceptors().add(in);
LoggingOutInterceptor out=new LoggingOutInterceptor();
bus.getOutInterceptors().add(out);
bus.getOutFaultInterceptors().add(out);
GreeterService gs=new GreeterService();
final Greeter greeter=gs.getGreeterPort();
updateAddressPort(greeter,PORT);
((BindingProvider)greeter).getRequestContext().put(Message.SCHEMA_VALIDATION_ENABLED,Boolean.TRUE);
LOG.fine("Created greeter client.");
ConnectionHelper.setKeepAliveConnection(greeter,true);
class TwowayThread extends Thread {
String response;
@Override public void run(){
response=greeter.greetMe("twoway");
}
}
TwowayThread t=new TwowayThread();
t.start();
long wait=3000;
while (wait > 0) {
long start=System.currentTimeMillis();
try {
Thread.sleep(wait);
}
catch ( InterruptedException ex) {
}
wait-=System.currentTimeMillis() - start;
}
greeter.greetMeOneWay("oneway");
t.join();
assertEquals("Unexpected response to twoway request","oneway",t.response);
}
Class: org.apache.cxf.systest.ws.rm.ManagedEndpointsTest APIUtilityVerifier IterativeVerifier BranchVerifier UtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testSuspendAndResumeSourceSequence() throws Exception {
prepareClient();
RMManager clientManager=clientBus.getExtension(RMManager.class);
InstrumentationManager serverIM=serverBus.getExtension(InstrumentationManager.class);
MBeanServer mbs=serverIM.getMBeanServer();
assertNotNull("MBeanServer must be available.",mbs);
Object o;
GreeterService gs=new GreeterService();
final Greeter greeter=gs.getGreeterPort();
updateAddressPort(greeter,ManagedEndpointsTest.PORT);
LOG.fine("Created greeter client.");
org.apache.cxf.endpoint.Endpoint ep=ClientProxy.getClient(greeter).getEndpoint();
ObjectName clientEndpointName=RMUtils.getManagedObjectName(clientManager,ep);
greeter.greetMeOneWay("one");
o=mbs.invoke(clientEndpointName,"getCurrentSourceSequenceId",null,null);
assertTrue(o instanceof String);
String sseqId=(String)o;
o=mbs.invoke(clientEndpointName,"getUnAcknowledgedMessageIdentifiers",new Object[]{sseqId},ONESTRING_SIGNATURE);
assertTrue("No unacknowledged message",o instanceof Long[] && 0 == ((Long[])o).length);
greeter.greetMeOneWay("two");
greeter.greetMeOneWay("three");
o=mbs.invoke(clientEndpointName,"getQueuedMessageTotalCount",new Object[]{true},ONEBOOLEAN_SIGNATURE);
assertTrue("One queued message",o instanceof Integer && 1 == ((Integer)o).intValue());
mbs.invoke(clientEndpointName,"suspendSourceQueue",new Object[]{sseqId},ONESTRING_SIGNATURE);
LOG.info("suspended the source queue: " + sseqId);
LOG.info("waiting for 4 secs for the retry (suspended)...");
Thread.sleep(4000);
o=mbs.invoke(clientEndpointName,"getQueuedMessageTotalCount",new Object[]{true},ONEBOOLEAN_SIGNATURE);
assertTrue("One queued message",o instanceof Integer && 1 == ((Integer)o).intValue());
mbs.invoke(clientEndpointName,"resumeSourceQueue",new Object[]{sseqId},ONESTRING_SIGNATURE);
LOG.info("resumed the source queue: " + sseqId);
o=mbs.invoke(clientEndpointName,"getQueuedMessageTotalCount",new Object[]{true},ONEBOOLEAN_SIGNATURE);
int count=0;
assertTrue(o instanceof Integer);
while (((Integer)o).intValue() > 0) {
Thread.sleep(200);
count++;
if (count > 100) {
fail("Failed to empty the resend queue");
}
o=mbs.invoke(clientEndpointName,"getQueuedMessageTotalCount",new Object[]{true},ONEBOOLEAN_SIGNATURE);
assertTrue(o instanceof Integer);
}
assertTrue("No queued messages",o instanceof Integer && 0 == ((Integer)o).intValue());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testManagedEndpointsOneway12() throws Exception {
prepareClient();
RMManager clientManager=clientBus.getExtension(RMManager.class);
RMManager serverManager=serverBus.getExtension(RMManager.class);
InstrumentationManager serverIM=serverBus.getExtension(InstrumentationManager.class);
MBeanServer mbs=serverIM.getMBeanServer();
assertNotNull("MBeanServer must be available.",mbs);
ObjectName clientManagerName=RMUtils.getManagedObjectName(clientManager);
ObjectName serverManagerName=RMUtils.getManagedObjectName(serverManager);
Object o;
GreeterService gs=new GreeterService();
final Greeter greeter=gs.getGreeterPort();
updateAddressPort(greeter,ManagedEndpointsTest.PORT);
LOG.fine("Created greeter client.");
ClientProxy.getClient(greeter).getRequestContext().put(RMManager.WSRM_VERSION_PROPERTY,RM11Constants.NAMESPACE_URI);
org.apache.cxf.endpoint.Endpoint ep=ClientProxy.getClient(greeter).getEndpoint();
String epId=RMUtils.getEndpointIdentifier(ep,clientBus);
greeter.greetMeOneWay("one");
o=mbs.invoke(clientManagerName,"getEndpointIdentifiers",null,null);
verifyArray("Expected endpoint identifier",o,new String[]{epId},true);
o=mbs.invoke(serverManagerName,"getEndpointIdentifiers",null,null);
verifyArray("Expected endpoint identifier",o,new String[]{epId},true);
ObjectName clientEndpointName=RMUtils.getManagedObjectName(clientManager,ep);
ObjectName serverEndpointName=getEndpointName(mbs,serverManager);
String sseqId=getSingleSourceSequenceId(mbs,clientEndpointName);
o=mbs.invoke(clientEndpointName,"getCurrentSourceSequenceId",null,null);
assertTrue("Expected sequence identifier",o instanceof String && sseqId.equals(o));
o=mbs.invoke(serverEndpointName,"getDestinationSequenceIds",null,null);
verifyArray("Expected sequence identifier",o,new String[]{sseqId},false);
String dseqId=getSingleDestinationSequenceId(mbs,clientEndpointName);
testOperation(mbs,greeter,clientEndpointName,serverEndpointName,sseqId,dseqId);
mbs.invoke(clientEndpointName,"closeSourceSequence",new Object[]{sseqId},ONESTRING_SIGNATURE);
o=mbs.invoke(clientEndpointName,"getSourceSequenceIds",new Object[]{true},ONEBOOLEAN_SIGNATURE);
verifyArray("Expected sequence identifier",o,new String[]{sseqId},true);
mbs.invoke(clientEndpointName,"terminateSourceSequence",new Object[]{sseqId},ONESTRING_SIGNATURE);
o=mbs.invoke(clientEndpointName,"getSourceSequenceIds",new Object[]{true},ONEBOOLEAN_SIGNATURE);
assertTrue("Source sequence terminated",o instanceof String[] && 0 == ((String[])o).length);
mbs.invoke(clientEndpointName,"terminateDestinationSequence",new Object[]{dseqId},ONESTRING_SIGNATURE);
o=mbs.invoke(clientEndpointName,"getDestinationSequenceIds",new Object[]{},EMPTY_SIGNATURE);
assertTrue("Destination sequence terminated",o instanceof String[] && 0 == ((String[])o).length);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testManagedEndpointsOneway() throws Exception {
prepareClient();
RMManager clientManager=clientBus.getExtension(RMManager.class);
RMManager serverManager=serverBus.getExtension(RMManager.class);
InstrumentationManager serverIM=serverBus.getExtension(InstrumentationManager.class);
MBeanServer mbs=serverIM.getMBeanServer();
assertNotNull("MBeanServer must be available.",mbs);
ObjectName clientManagerName=RMUtils.getManagedObjectName(clientManager);
ObjectName serverManagerName=RMUtils.getManagedObjectName(serverManager);
Object o;
GreeterService gs=new GreeterService();
final Greeter greeter=gs.getGreeterPort();
updateAddressPort(greeter,ManagedEndpointsTest.PORT);
LOG.fine("Created greeter client.");
org.apache.cxf.endpoint.Endpoint ep=ClientProxy.getClient(greeter).getEndpoint();
String epId=RMUtils.getEndpointIdentifier(ep,clientBus);
greeter.greetMeOneWay("one");
o=mbs.invoke(clientManagerName,"getEndpointIdentifiers",null,null);
verifyArray("Expected endpoint identifier",o,new String[]{epId},true);
o=mbs.invoke(serverManagerName,"getEndpointIdentifiers",null,null);
verifyArray("Expected endpoint identifier",o,new String[]{epId},true);
ObjectName clientEndpointName=RMUtils.getManagedObjectName(clientManager,ep);
ObjectName serverEndpointName=getEndpointName(mbs,serverManager);
String sseqId=getSingleSourceSequenceId(mbs,clientEndpointName);
o=mbs.invoke(clientEndpointName,"getCurrentSourceSequenceId",null,null);
assertTrue("Expected sequence identifier",o instanceof String && sseqId.equals(o));
o=mbs.invoke(serverEndpointName,"getDestinationSequenceIds",null,null);
verifyArray("Expected sequence identifier",o,new String[]{sseqId},false);
String dseqId=getSingleDestinationSequenceId(mbs,clientEndpointName);
testOperation(mbs,greeter,clientEndpointName,serverEndpointName,sseqId,dseqId);
mbs.invoke(clientEndpointName,"terminateSourceSequence",new Object[]{sseqId},ONESTRING_SIGNATURE);
o=mbs.invoke(clientEndpointName,"getSourceSequenceIds",new Object[]{true},ONEBOOLEAN_SIGNATURE);
assertTrue("Source sequence terminated",o instanceof String[] && 0 == ((String[])o).length);
mbs.invoke(clientEndpointName,"terminateDestinationSequence",new Object[]{dseqId},ONESTRING_SIGNATURE);
o=mbs.invoke(clientEndpointName,"getDestinationSequenceIds",new Object[]{},EMPTY_SIGNATURE);
assertTrue("Destination sequence terminated",o instanceof String[] && 0 == ((String[])o).length);
}
Class: org.apache.cxf.systest.ws.rm.ProtocolVariationsTest InternalCallVerifier EqualityVerifier
@Test public void testDefaultDecoupled() throws Exception {
init("org/apache/cxf/systest/ws/rm/rminterceptors.xml",true);
assertEquals("ONE",greeter.greetMe("one"));
assertEquals("TWO",greeter.greetMe("two"));
assertEquals("THREE",greeter.greetMe("three"));
verifyTwowayNonAnonymous(Names200408.WSA_NAMESPACE_NAME,RM10Constants.INSTANCE);
}
InternalCallVerifier EqualityVerifier
@Test public void testDefault() throws Exception {
init("org/apache/cxf/systest/ws/rm/rminterceptors.xml",false);
assertEquals("ONE",greeter.greetMe("one"));
assertEquals("TWO",greeter.greetMe("two"));
assertEquals("THREE",greeter.greetMe("three"));
verifyTwowayNonAnonymous(Names200408.WSA_NAMESPACE_NAME,RM10Constants.INSTANCE);
}
InternalCallVerifier EqualityVerifier
@Test public void testRM11() throws Exception {
init("org/apache/cxf/systest/ws/rm/rminterceptors.xml",false);
Client client=ClientProxy.getClient(greeter);
client.getRequestContext().put(RMManager.WSRM_VERSION_PROPERTY,RM11Constants.NAMESPACE_URI);
client.getRequestContext().put(RMManager.WSRM_WSA_VERSION_PROPERTY,Names.WSA_NAMESPACE_NAME);
assertEquals("ONE",greeter.greetMe("one"));
assertEquals("TWO",greeter.greetMe("two"));
assertEquals("THREE",greeter.greetMe("three"));
verifyTwowayNonAnonymous(Names.WSA_NAMESPACE_NAME,RM11Constants.INSTANCE);
}
InternalCallVerifier EqualityVerifier
@Test public void testRM10WSA200408Decoupled() throws Exception {
init("org/apache/cxf/systest/ws/rm/rminterceptors.xml",true);
Client client=ClientProxy.getClient(greeter);
client.getRequestContext().put(RMManager.WSRM_WSA_VERSION_PROPERTY,Names200408.WSA_NAMESPACE_NAME);
assertEquals("ONE",greeter.greetMe("one"));
assertEquals("TWO",greeter.greetMe("two"));
assertEquals("THREE",greeter.greetMe("three"));
verifyTwowayNonAnonymous(Names200408.WSA_NAMESPACE_NAME,RM10Constants.INSTANCE);
}
InternalCallVerifier EqualityVerifier
@Test public void testRM10WSA200408() throws Exception {
init("org/apache/cxf/systest/ws/rm/rminterceptors.xml",false);
Client client=ClientProxy.getClient(greeter);
client.getRequestContext().put(RMManager.WSRM_WSA_VERSION_PROPERTY,Names200408.WSA_NAMESPACE_NAME);
assertEquals("ONE",greeter.greetMe("one"));
assertEquals("TWO",greeter.greetMe("two"));
assertEquals("THREE",greeter.greetMe("three"));
verifyTwowayNonAnonymous(Names200408.WSA_NAMESPACE_NAME,RM10Constants.INSTANCE);
}
InternalCallVerifier EqualityVerifier
@Test public void testRM11Decoupled() throws Exception {
init("org/apache/cxf/systest/ws/rm/rminterceptors.xml",true);
Client client=ClientProxy.getClient(greeter);
client.getRequestContext().put(RMManager.WSRM_VERSION_PROPERTY,RM11Constants.NAMESPACE_URI);
client.getRequestContext().put(RMManager.WSRM_WSA_VERSION_PROPERTY,Names.WSA_NAMESPACE_NAME);
assertEquals("ONE",greeter.greetMe("one"));
assertEquals("TWO",greeter.greetMe("two"));
assertEquals("THREE",greeter.greetMe("three"));
verifyTwowayNonAnonymous(Names.WSA_NAMESPACE_NAME,RM11Constants.INSTANCE);
}
InternalCallVerifier EqualityVerifier
@Test public void testRM10WSA15() throws Exception {
init("org/apache/cxf/systest/ws/rm/rminterceptors.xml",false);
Client client=ClientProxy.getClient(greeter);
client.getRequestContext().put(RMManager.WSRM_WSA_VERSION_PROPERTY,Names.WSA_NAMESPACE_NAME);
assertEquals("ONE",greeter.greetMe("one"));
assertEquals("TWO",greeter.greetMe("two"));
assertEquals("THREE",greeter.greetMe("three"));
verifyTwowayNonAnonymous(Names.WSA_NAMESPACE_NAME,RM10Constants.INSTANCE);
}
InternalCallVerifier EqualityVerifier
@Test public void testRM10WSA15Decoupled() throws Exception {
init("org/apache/cxf/systest/ws/rm/rminterceptors.xml",true);
Client client=ClientProxy.getClient(greeter);
client.getRequestContext().put(RMManager.WSRM_WSA_VERSION_PROPERTY,Names.WSA_NAMESPACE_NAME);
assertEquals("ONE",greeter.greetMe("one"));
assertEquals("TWO",greeter.greetMe("two"));
assertEquals("THREE",greeter.greetMe("three"));
verifyTwowayNonAnonymous(Names.WSA_NAMESPACE_NAME,RM10Constants.INSTANCE);
}
Class: org.apache.cxf.systest.ws.rm.RetransmissionGZIPTest UtilityVerifier BooleanVerifier InternalCallVerifier HybridVerifier
@Test public void testDecoupleFaultHandling() throws Exception {
SpringBusFactory bf=new SpringBusFactory();
bus=bf.createBus("/org/apache/cxf/systest/ws/rm/gzip-enabled.xml");
BusFactory.setDefaultBus(bus);
LoggingInInterceptor in=new LoggingInInterceptor();
bus.getInInterceptors().add(in);
bus.getInFaultInterceptors().add(in);
LoggingOutInterceptor out=new LoggingOutInterceptor();
bus.getOutInterceptors().add(out);
bus.getExtension(RMManager.class).getConfiguration().setBaseRetransmissionInterval(new Long(4000));
MessageLossSimulator loser=new MessageLossSimulator();
bus.getOutInterceptors().add(loser);
bus.getOutFaultInterceptors().add(out);
GreeterService gs=new GreeterService();
final Greeter greeter=gs.getGreeterPort();
updateAddressPort(greeter,PORT);
LOG.fine("Created greeter client.");
ConnectionHelper.setKeepAliveConnection(greeter,true);
loser.setMode(-1);
loser.setThrowsException(true);
try {
greeter.greetMeOneWay("oneway");
}
catch ( Exception e) {
fail("fault thrown after queued for retransmission");
}
Thread.sleep(2000);
RMManager manager=bus.getExtension(RMManager.class);
boolean empty=manager.getRetransmissionQueue().isEmpty();
assertFalse("RetransmissionQueue is empty",empty);
loser.setMode(1);
Thread.sleep(6000);
empty=manager.getRetransmissionQueue().isEmpty();
assertTrue("RetransmissionQueue not cleared",empty);
}
Class: org.apache.cxf.systest.ws.rm.RetransmissionQueueTest UtilityVerifier BooleanVerifier InternalCallVerifier HybridVerifier
@Test public void testDecoupleFaultHandling() throws Exception {
SpringBusFactory bf=new SpringBusFactory();
bus=bf.createBus("/org/apache/cxf/systest/ws/rm/message-loss.xml");
BusFactory.setDefaultBus(bus);
LoggingInInterceptor in=new LoggingInInterceptor();
bus.getInInterceptors().add(in);
bus.getInFaultInterceptors().add(in);
LoggingOutInterceptor out=new LoggingOutInterceptor();
bus.getOutInterceptors().add(out);
bus.getExtension(RMManager.class).getConfiguration().setBaseRetransmissionInterval(new Long(4000));
MessageLossSimulator loser=new MessageLossSimulator();
bus.getOutInterceptors().add(loser);
bus.getOutFaultInterceptors().add(out);
GreeterService gs=new GreeterService();
final Greeter greeter=gs.getGreeterPort();
updateAddressPort(greeter,PORT);
LOG.fine("Created greeter client.");
ConnectionHelper.setKeepAliveConnection(greeter,true);
loser.setMode(-1);
loser.setThrowsException(true);
try {
greeter.greetMeOneWay("oneway");
}
catch ( Exception e) {
fail("fault thrown after queued for retransmission");
}
Thread.sleep(2000);
RMManager manager=bus.getExtension(RMManager.class);
boolean empty=manager.getRetransmissionQueue().isEmpty();
assertFalse("RetransmissionQueue is empty",empty);
loser.setMode(1);
Thread.sleep(6000);
empty=manager.getRetransmissionQueue().isEmpty();
assertTrue("RetransmissionQueue not cleared",empty);
}
Class: org.apache.cxf.systest.ws.rm.RobustServiceAtMostOnceTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testRobustAtMostOnceWithSlowProcessing() throws Exception {
LOG.fine("Creating greeter client");
SpringBusFactory bf=new SpringBusFactory();
bus=bf.createBus("/org/apache/cxf/systest/ws/rm/seqlength1.xml");
RMManager manager=bus.getExtension(RMManager.class);
manager.getConfiguration().setBaseRetransmissionInterval(new Long(3000));
BusFactory.setDefaultBus(bus);
GreeterService gs=new GreeterService();
greeter=gs.getGreeterPort();
updateAddressPort(greeter,PORT);
LOG.fine("Invoking greeter");
greeter.greetMeOneWay("one");
Thread.sleep(10000);
assertEquals("invoked too many times",1,serverGreeter.getCount());
assertTrue("still in retransmission",manager.getRetransmissionQueue().isEmpty());
}
Class: org.apache.cxf.systest.ws.rm.RobustServiceWithFaultTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testRobustWithSomeFaults() throws Exception {
LOG.fine("Creating greeter client");
SpringBusFactory bf=new SpringBusFactory();
bus=bf.createBus("/org/apache/cxf/systest/ws/rm/seqlength1.xml");
RMManager manager=bus.getExtension(RMManager.class);
manager.getConfiguration().setBaseRetransmissionInterval(new Long(5000));
BusFactory.setDefaultBus(bus);
GreeterService gs=new GreeterService();
greeter=gs.getGreeterPort();
updateAddressPort(greeter,PORT);
LOG.fine("Invoking greeter");
greeter.greetMeOneWay("one");
Thread.sleep(3000);
assertEquals("not invoked once",1,serverGreeter.getCount());
assertTrue("still in retransmission",manager.getRetransmissionQueue().isEmpty());
LOG.fine("Invoking greeter and raising a fault");
serverGreeter.setThrowAlways(true);
greeter.greetMeOneWay("two");
Thread.sleep(3000);
assertEquals("not invoked once",1,serverGreeter.getCount());
assertTrue("still in retransmission",manager.getRetransmissionQueue().isEmpty());
LOG.fine("Invoking robust greeter and raising a fault");
robustSetter.setRobust(true);
greeter.greetMeOneWay("three");
Thread.sleep(3000);
assertEquals("not invoked once",1,serverGreeter.getCount());
assertFalse("no message in retransmission",manager.getRetransmissionQueue().isEmpty());
LOG.fine("Stop raising a fault and let the retransmission succeeds");
serverGreeter.setThrowAlways(false);
Thread.sleep(8000);
assertEquals("not invoked twice",2,serverGreeter.getCount());
assertTrue("still in retransmission",manager.getRetransmissionQueue().isEmpty());
}
Class: org.apache.cxf.systest.ws.rm.SequenceTest APIUtilityVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testInactivityTimeout() throws Exception {
init("org/apache/cxf/systest/ws/rm/inactivity-timeout.xml");
greeter.greetMe("one");
try {
Thread.sleep(500);
}
catch ( InterruptedException ex) {
}
try {
greeter.greetMe("two");
fail("Expected fault.");
}
catch ( WebServiceException ex) {
SoapFault sf=(SoapFault)ex.getCause();
assertEquals("Unexpected fault code.",Soap11.getInstance().getSender(),sf.getFaultCode());
assertNull("Unexpected sub code.",sf.getSubCode());
assertTrue("Unexpected reason.",sf.getReason().endsWith("is not a known Sequence identifier."));
}
awaitMessages(3,3,5000);
MessageFlow mf=new MessageFlow(outRecorder.getOutboundMessages(),inRecorder.getInboundMessages(),Names200408.WSA_NAMESPACE_NAME,RM10Constants.NAMESPACE_URI);
String[] expectedActions=new String[3];
expectedActions[0]=RM10Constants.CREATE_SEQUENCE_ACTION;
for (int i=1; i < expectedActions.length; i++) {
expectedActions[i]=GREETME_ACTION;
}
mf.verifyActions(expectedActions,true);
mf.verifyMessageNumbers(new String[]{null,"1","2"},true);
mf.verifyLastMessage(new boolean[3],true);
mf.verifyAcknowledgements(new boolean[]{false,false,false},true);
mf.verifyMessages(3,false);
expectedActions=new String[]{RM10Constants.CREATE_SEQUENCE_RESPONSE_ACTION,GREETME_RESPONSE_ACTION,RM10_GENERIC_FAULT_ACTION};
mf.verifyActions(expectedActions,false);
mf.verifyMessageNumbers(new String[]{null,"1",null},false);
mf.verifyAcknowledgements(new boolean[]{false,true,false},false);
mf.verifySequenceFault(RM10Constants.UNKNOWN_SEQUENCE_FAULT_QNAME,false,2);
}
InternalCallVerifier EqualityVerifier
@Test public void testCreateSequenceAfterSequenceExpiration() throws Exception {
init("org/apache/cxf/systest/ws/rm/expire-fast-seq.xml",true);
RMManager manager=greeterBus.getExtension(RMManager.class);
assertEquals("Unexpected expiration",DatatypeFactory.createDuration("PT5S"),manager.getSourcePolicy().getSequenceExpiration());
greeter.greetMeOneWay("one");
greeter.greetMeOneWay("two");
Thread.sleep(8000);
awaitMessages(3,2,5000);
MessageFlow mf=new MessageFlow(outRecorder.getOutboundMessages(),inRecorder.getInboundMessages(),Names200408.WSA_NAMESPACE_NAME,RM10Constants.NAMESPACE_URI);
mf.verifyMessages(3,true);
verifyCreateSequenceAction(0,"PT5S",mf,true);
String[] expectedActions=new String[]{RM10Constants.INSTANCE.getCreateSequenceAction(),GREETMEONEWAY_ACTION,GREETMEONEWAY_ACTION};
mf.verifyActions(expectedActions,true);
mf.verifyMessageNumbers(new String[]{null,"1","2"},true);
mf.verifyAcknowledgementRange(1,2);
outRecorder.getOutboundMessages().clear();
inRecorder.getInboundMessages().clear();
greeter.greetMeOneWay("three");
awaitMessages(2,2,5000);
mf=new MessageFlow(outRecorder.getOutboundMessages(),inRecorder.getInboundMessages(),Names200408.WSA_NAMESPACE_NAME,RM10Constants.NAMESPACE_URI);
mf.verifyMessages(2,true);
verifyCreateSequenceAction(0,"PT5S",mf,true);
expectedActions=new String[]{RM10Constants.INSTANCE.getCreateSequenceAction(),GREETMEONEWAY_ACTION};
mf.verifyActions(expectedActions,true);
mf.verifyMessageNumbers(new String[]{null,"1"},true);
mf.verifyMessages(2,false);
expectedActions=new String[]{RM10Constants.INSTANCE.getCreateSequenceResponseAction(),RM10Constants.INSTANCE.getSequenceAckAction()};
mf.verifyActions(expectedActions,false);
mf.purge();
assertEquals(0,outRecorder.getOutboundMessages().size());
assertEquals(0,inRecorder.getInboundMessages().size());
}
InternalCallVerifier EqualityVerifier
@Test public void testTwowayNonAnonymousMaximumSequenceLength2() throws Exception {
init("org/apache/cxf/systest/ws/rm/seqlength10.xml",true);
RMManager manager=greeterBus.getExtension(RMManager.class);
assertEquals("Unexpected maximum sequence length.",10,manager.getSourcePolicy().getSequenceTerminationPolicy().getMaxLength());
manager.getSourcePolicy().getSequenceTerminationPolicy().setMaxLength(2);
greeter.greetMe("one");
greeter.greetMe("two");
greeter.greetMe("three");
awaitMessages(7,6,5000);
MessageFlow mf=new MessageFlow(outRecorder.getOutboundMessages(),inRecorder.getInboundMessages(),Names200408.WSA_NAMESPACE_NAME,RM10Constants.NAMESPACE_URI);
mf.verifyMessages(7,true);
String[] expectedActions=new String[]{RM10Constants.CREATE_SEQUENCE_ACTION,GREETME_ACTION,GREETME_ACTION,RM10Constants.TERMINATE_SEQUENCE_ACTION,RM10Constants.SEQUENCE_ACKNOWLEDGMENT_ACTION,RM10Constants.CREATE_SEQUENCE_ACTION,GREETME_ACTION};
mf.verifyActions(expectedActions,true);
mf.verifyMessageNumbers(new String[]{null,"1","2",null,null,null,"1"},true);
mf.verifyLastMessage(new boolean[]{false,false,true,false,false,false,false},true);
mf.verifyAcknowledgements(new boolean[]{false,false,true,false,true,false,false},true);
mf.verifyMessages(6,false);
expectedActions=new String[]{RM10Constants.CREATE_SEQUENCE_RESPONSE_ACTION,GREETME_RESPONSE_ACTION,GREETME_RESPONSE_ACTION,RM10Constants.TERMINATE_SEQUENCE_ACTION,RM10Constants.CREATE_SEQUENCE_RESPONSE_ACTION,GREETME_RESPONSE_ACTION};
mf.verifyActions(expectedActions,false);
mf.verifyMessageNumbers(new String[]{null,"1","2",null,null,"1"},false);
boolean[] expected=new boolean[6];
expected[2]=true;
mf.verifyLastMessage(expected,false);
expected[1]=true;
expected[5]=true;
mf.verifyAcknowledgements(expected,false);
}
APIUtilityVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testUnknownSequence() throws Exception {
init("org/apache/cxf/systest/ws/rm/rminterceptors.xml");
class SequenceIdInterceptor extends AbstractPhaseInterceptor {
SequenceIdInterceptor(){
super(Phase.PRE_STREAM);
}
public void handleMessage( Message m){
RMProperties rmps=RMContextUtils.retrieveRMProperties(m,true);
if (null != rmps && null != rmps.getSequence()) {
rmps.getSequence().getIdentifier().setValue("UNKNOWN");
}
}
}
greeterBus.getOutInterceptors().add(new SequenceIdInterceptor());
RMManager manager=greeterBus.getExtension(RMManager.class);
manager.getConfiguration().setBaseRetransmissionInterval(new Long(2000));
try {
greeter.greetMe("one");
fail("Expected fault.");
}
catch ( WebServiceException ex) {
SoapFault sf=(SoapFault)ex.getCause();
assertEquals("Unexpected fault code.",Soap11.getInstance().getSender(),sf.getFaultCode());
assertNull("Unexpected sub code.",sf.getSubCode());
assertTrue("Unexpected reason.",sf.getReason().endsWith("is not a known Sequence identifier."));
}
MessageFlow mf=new MessageFlow(outRecorder.getOutboundMessages(),inRecorder.getInboundMessages(),Names200408.WSA_NAMESPACE_NAME,RM10Constants.NAMESPACE_URI);
mf.verifySequenceFault(RM10Constants.UNKNOWN_SEQUENCE_FAULT_QNAME,false,1);
String[] expectedActions=new String[3];
expectedActions=new String[]{RM10Constants.CREATE_SEQUENCE_RESPONSE_ACTION,RM10_GENERIC_FAULT_ACTION};
mf.verifyActions(expectedActions,false);
}
InternalCallVerifier EqualityVerifier
@Test public void testTwowayNonAnonymousProvider() throws Exception {
init("org/apache/cxf/systest/ws/rm/rminterceptors_provider.xml",true);
assertEquals("ONE",greeter.greetMe("one"));
assertEquals("TWO",greeter.greetMe("two"));
assertEquals("THREE",greeter.greetMe("three"));
}
InternalCallVerifier EqualityVerifier
@Test public void testTwowayAnonymousSequenceLength1() throws Exception {
init("org/apache/cxf/systest/ws/rm/seqlength1.xml");
String v=greeter.greetMe("once");
assertEquals("Unexpected response","ONCE",v);
awaitMessages(4,3);
MessageFlow mf=new MessageFlow(outRecorder.getOutboundMessages(),inRecorder.getInboundMessages(),Names200408.WSA_NAMESPACE_NAME,RM10Constants.NAMESPACE_URI);
mf.verifyMessages(4,true);
String[] expectedActions=new String[]{RM10Constants.CREATE_SEQUENCE_ACTION,GREETME_ACTION,RM10Constants.TERMINATE_SEQUENCE_ACTION,RM10Constants.SEQUENCE_ACKNOWLEDGMENT_ACTION};
mf.verifyActions(expectedActions,true);
mf.verifyMessageNumbers(new String[]{null,"1",null,null},true);
mf.verifyLastMessage(new boolean[]{false,true,false,false},true);
mf.verifyAcknowledgements(new boolean[]{false,false,false,true},true);
mf.verifyMessages(3,false);
expectedActions=new String[]{RM10Constants.CREATE_SEQUENCE_RESPONSE_ACTION,GREETME_RESPONSE_ACTION,RM10Constants.TERMINATE_SEQUENCE_ACTION};
mf.verifyActions(expectedActions,false);
mf.verifyMessageNumbers(new String[]{null,"1",null},false);
mf.verifyLastMessage(new boolean[]{false,true,false},false);
mf.verifyAcknowledgements(new boolean[]{false,true,false},false);
}
UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testCreateSequenceRefused() throws Exception {
init("org/apache/cxf/systest/ws/rm/limit-seqs.xml");
RMManager manager=greeterBus.getExtension(RMManager.class);
assertEquals("Unexpected maximum sequence count.",1,manager.getDestinationPolicy().getMaxSequences());
greeter.greetMe("one");
Closeable oldGreeter=(Closeable)greeter;
initProxy(false,null);
try {
greeter.greetMe("two");
fail("Expected fault.");
}
catch ( WebServiceException ex) {
}
MessageFlow mf=new MessageFlow(outRecorder.getOutboundMessages(),inRecorder.getInboundMessages(),Names200408.WSA_NAMESPACE_NAME,RM10Constants.NAMESPACE_URI);
mf.verifySequenceFault(RM10Constants.CREATE_SEQUENCE_REFUSED_FAULT_QNAME,false,2);
String[] expectedActions=new String[3];
expectedActions=new String[]{RM10Constants.CREATE_SEQUENCE_RESPONSE_ACTION,GREETME_RESPONSE_ACTION,RM10_GENERIC_FAULT_ACTION};
mf.verifyActions(expectedActions,false);
oldGreeter.close();
}
InternalCallVerifier EqualityVerifier
@Test public void testTwowayNonAnonymous() throws Exception {
init("org/apache/cxf/systest/ws/rm/rminterceptors.xml",true);
assertEquals("ONE",greeter.greetMe("one"));
assertEquals("TWO",greeter.greetMe("two"));
assertEquals("THREE",greeter.greetMe("three"));
verifyTwowayNonAnonymous();
}
Class: org.apache.cxf.systest.ws.rm.ServiceInvocationAckBase TestCleaner BranchVerifier BooleanVerifier InternalCallVerifier HybridVerifier
@After public void tearDown(){
if (null != greeter) {
assertTrue("Failed to stop greeter.",control.stopGreeter(null));
greeterBus.shutdown(true);
greeterBus=null;
}
if (null != control) {
assertTrue("Failed to stop greeter",control.stopGreeter(null));
controlBus.shutdown(true);
}
}
Class: org.apache.cxf.systest.ws.rm.WSRMPolicyResolveTest InternalCallVerifier EqualityVerifier
@Test public void testHello() throws Exception {
BasicDocEndpoint port=getApplicationContext().getBean("TestClient",BasicDocEndpoint.class);
Object retObj=port.echo("Hello");
assertEquals("Hello",retObj);
}
Class: org.apache.cxf.systest.ws.rm.policy.WSRMOptionalPolicyTest BooleanVerifier InternalCallVerifier
@Test public void testBasicConnection() throws Exception {
Greeting service=createService();
assertTrue("Hello, cxf!".equals(service.hello("cxf")));
assertTrue("Goodbye, cxf!".equals(service.goodbye("cxf")));
}
Class: org.apache.cxf.systest.ws.rm.sec.WSRMWithWSSecurityPolicyTest BooleanVerifier InternalCallVerifier
@Test public void testWithSecurityInPolicy() throws Exception {
LOG.fine("Creating greeter client");
ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("org/apache/cxf/systest/ws/rm/sec/client-policy.xml");
Bus bus=(Bus)context.getBean("bus");
BusFactory.setDefaultBus(bus);
BusFactory.setThreadDefaultBus(bus);
Greeter greeter=(Greeter)context.getBean("GreeterCombinedClient");
RMManager manager=bus.getExtension(RMManager.class);
boolean empty=manager.getRetransmissionQueue().isEmpty();
assertTrue("RetransmissionQueue is not empty",empty);
LOG.fine("Invoking greeter");
greeter.greetMeOneWay("one");
Thread.sleep(3000);
empty=manager.getRetransmissionQueue().isEmpty();
assertTrue("RetransmissionQueue not empty",empty);
context.close();
}
Class: org.apache.cxf.systest.ws.security.SecurityPolicyTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testDispatchClient() throws Exception {
SpringBusFactory bf=new SpringBusFactory();
Bus bus=bf.createBus();
SpringBusFactory.setDefaultBus(bus);
SpringBusFactory.setThreadDefaultBus(bus);
URL wsdl=SecurityPolicyTest.class.getResource("DoubleIt.wsdl");
Service service=Service.create(wsdl,SERVICE_QNAME);
QName portQName=new QName(NAMESPACE,"DoubleItPortEncryptThenSign");
Dispatch disp=service.createDispatch(portQName,Source.class,Mode.PAYLOAD);
disp.getRequestContext().put(SecurityConstants.CALLBACK_HANDLER,new KeystorePasswordCallback());
disp.getRequestContext().put(SecurityConstants.SIGNATURE_PROPERTIES,"alice.properties");
disp.getRequestContext().put(SecurityConstants.ENCRYPT_PROPERTIES,"bob.properties");
updateAddressPort(disp,PORT);
String req="" + "25 ";
Source source=new StreamSource(new StringReader(req));
source=disp.invoke(source);
Node nd=StaxUtils.read(source);
if (nd instanceof Document) {
nd=((Document)nd).getDocumentElement();
}
Map ns=new HashMap();
ns.put("ns2","http://www.example.org/schema/DoubleIt");
XPathUtils xp=new XPathUtils(ns);
Object o=xp.getValue("//ns2:DoubleItResponse/doubledNumber",nd,XPathConstants.STRING);
assertEquals(StaxUtils.toString(nd),"50",o);
bus.shutdown(true);
}
APIUtilityVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testSignedOnlyWithUnsignedMessage() throws Exception {
SpringBusFactory bf=new SpringBusFactory();
Bus bus=bf.createBus();
SpringBusFactory.setDefaultBus(bus);
SpringBusFactory.setThreadDefaultBus(bus);
URL wsdl=SecurityPolicyTest.class.getResource("DoubleIt.wsdl");
Service service=Service.create(wsdl,SERVICE_QNAME);
DoubleItPortType pt;
QName portQName=new QName(NAMESPACE,"DoubleItPortSignedOnly");
pt=service.getPort(portQName,DoubleItPortType.class);
updateAddressPort(pt,PORT);
((BindingProvider)pt).getRequestContext().put(SecurityConstants.CALLBACK_HANDLER,new KeystorePasswordCallback());
((BindingProvider)pt).getRequestContext().put(SecurityConstants.SIGNATURE_PROPERTIES,"alice.properties");
((BindingProvider)pt).getRequestContext().put(SecurityConstants.ENCRYPT_PROPERTIES,"bob.properties");
assertEquals(10,pt.doubleIt(5));
SecurityTestUtil.enableStreaming(pt);
assertEquals(10,pt.doubleIt(5));
((java.io.Closeable)pt).close();
portQName=new QName(NAMESPACE,"DoubleItPortTimestampOnly");
pt=service.getPort(portQName,DoubleItPortType.class);
((BindingProvider)pt).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,POLICY_SIGNONLY_ADDRESS);
try {
pt.doubleIt(5);
fail("should have had a security/policy exception as the body wasn't signed");
}
catch ( Exception ex) {
assertTrue(ex.getMessage().contains("policy alternatives"));
}
try {
SecurityTestUtil.enableStreaming(pt);
pt.doubleIt(5);
fail("should have had a security/policy exception as the body wasn't signed");
}
catch ( Exception ex) {
}
((java.io.Closeable)pt).close();
bus.shutdown(true);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testCXF3041() throws Exception {
SpringBusFactory bf=new SpringBusFactory();
Bus bus=bf.createBus();
SpringBusFactory.setDefaultBus(bus);
SpringBusFactory.setThreadDefaultBus(bus);
URL wsdl=SecurityPolicyTest.class.getResource("DoubleIt.wsdl");
Service service=Service.create(wsdl,SERVICE_QNAME);
DoubleItPortType pt;
QName portQName=new QName(NAMESPACE,"DoubleItPortCXF3041");
pt=service.getPort(portQName,DoubleItPortType.class);
updateAddressPort(pt,PORT);
((BindingProvider)pt).getRequestContext().put(SecurityConstants.CALLBACK_HANDLER,new KeystorePasswordCallback());
((BindingProvider)pt).getRequestContext().put(SecurityConstants.SIGNATURE_PROPERTIES,"alice.properties");
((BindingProvider)pt).getRequestContext().put(SecurityConstants.ENCRYPT_PROPERTIES,"bob.properties");
assertEquals(10,pt.doubleIt(5));
SecurityTestUtil.enableStreaming(pt);
assertEquals(10,pt.doubleIt(5));
((java.io.Closeable)pt).close();
bus.shutdown(true);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testCXF3042() throws Exception {
SpringBusFactory bf=new SpringBusFactory();
Bus bus=bf.createBus();
SpringBusFactory.setDefaultBus(bus);
SpringBusFactory.setThreadDefaultBus(bus);
URL wsdl=SecurityPolicyTest.class.getResource("DoubleIt.wsdl");
Service service=Service.create(wsdl,SERVICE_QNAME);
DoubleItPortType pt;
QName portQName=new QName(NAMESPACE,"DoubleItPortCXF3042");
pt=service.getPort(portQName,DoubleItPortType.class);
updateAddressPort(pt,PORT);
((BindingProvider)pt).getRequestContext().put(SecurityConstants.CALLBACK_HANDLER,new KeystorePasswordCallback());
((BindingProvider)pt).getRequestContext().put(SecurityConstants.SIGNATURE_PROPERTIES,"alice.properties");
((BindingProvider)pt).getRequestContext().put(SecurityConstants.ENCRYPT_PROPERTIES,"alice.properties");
assertEquals(10,pt.doubleIt(5));
SecurityTestUtil.enableStreaming(pt);
assertEquals(10,pt.doubleIt(5));
((java.io.Closeable)pt).close();
bus.shutdown(true);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testCXF3452() throws Exception {
SpringBusFactory bf=new SpringBusFactory();
Bus bus=bf.createBus();
SpringBusFactory.setDefaultBus(bus);
SpringBusFactory.setThreadDefaultBus(bus);
URL wsdl=SecurityPolicyTest.class.getResource("DoubleIt.wsdl");
Service service=Service.create(wsdl,SERVICE_QNAME);
DoubleItPortTypeHeader pt;
QName portQName=new QName(NAMESPACE,"DoubleItPortCXF3452");
pt=service.getPort(portQName,DoubleItPortTypeHeader.class);
updateAddressPort(pt,PORT);
((BindingProvider)pt).getRequestContext().put(SecurityConstants.CALLBACK_HANDLER,new KeystorePasswordCallback());
((BindingProvider)pt).getRequestContext().put(SecurityConstants.SIGNATURE_PROPERTIES,"alice.properties");
((BindingProvider)pt).getRequestContext().put(SecurityConstants.ENCRYPT_PROPERTIES,"alice.properties");
DoubleIt di=new DoubleIt();
di.setNumberToDouble(5);
assertEquals(10,pt.doubleIt(di,1).getDoubledNumber());
((java.io.Closeable)pt).close();
bus.shutdown(true);
}
Class: org.apache.cxf.systest.ws.security.WSSecurityClientTest APIUtilityVerifier UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testUsernameToken() throws Exception {
final javax.xml.ws.Service svc=javax.xml.ws.Service.create(WSDL_LOC,GREETER_SERVICE_QNAME);
final Greeter greeter=svc.getPort(USERNAME_TOKEN_PORT_QNAME,Greeter.class);
updateAddressPort(greeter,test.getPort());
Client client=ClientProxy.getClient(greeter);
Map props=new HashMap();
props.put("action","UsernameToken");
props.put("user","alice");
props.put("passwordType","PasswordText");
WSS4JOutInterceptor wss4jOut=new WSS4JOutInterceptor(props);
client.getOutInterceptors().add(wss4jOut);
((BindingProvider)greeter).getRequestContext().put("password","password");
try {
greeter.greetMe("CXF");
fail("should fail because of password text instead of digest");
}
catch ( Exception ex) {
}
props.put("passwordType","PasswordDigest");
String s=greeter.greetMe("CXF");
assertEquals("Hello CXF",s);
try {
((BindingProvider)greeter).getRequestContext().put("password","foo");
greeter.greetMe("CXF");
fail("should fail");
}
catch ( Exception ex) {
}
try {
props.put("passwordType","PasswordText");
((BindingProvider)greeter).getRequestContext().put("password","password");
greeter.greetMe("CXF");
fail("should fail");
}
catch ( Exception ex) {
}
((java.io.Closeable)greeter).close();
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testMalformedSecurityHeaders() throws java.lang.Exception {
Dispatch dispatcher=null;
java.io.InputStream is=null;
String result=null;
dispatcher=createUsernameTokenDispatcher(test.getPort());
is=getClass().getResourceAsStream("test-data/UsernameTokenRequest.xml");
result=source2String(dispatcher.invoke(new StreamSource(is)));
assertTrue(result.indexOf("Fault") != -1);
dispatcher=createUsernameTokenDispatcher(test.getPort());
is=getClass().getResourceAsStream("test-data/NoHeadersRequest.xml");
result=source2String(dispatcher.invoke(new StreamSource(is)));
assertTrue(result.indexOf("Fault") != -1);
dispatcher=createUsernameTokenDispatcher(test.getPort());
is=getClass().getResourceAsStream("test-data/EmptyHeaderRequest.xml");
result=source2String(dispatcher.invoke(new StreamSource(is)));
assertTrue(result.indexOf("Fault") != -1);
dispatcher=createUsernameTokenDispatcher(test.getPort());
is=getClass().getResourceAsStream("test-data/EmptySecurityHeaderRequest.xml");
result=source2String(dispatcher.invoke(new StreamSource(is)));
assertTrue(result.indexOf("Fault") != -1);
}
APIUtilityVerifier UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testUsernameTokenStreaming() throws Exception {
final javax.xml.ws.Service svc=javax.xml.ws.Service.create(WSDL_LOC,GREETER_SERVICE_QNAME);
final Greeter greeter=svc.getPort(USERNAME_TOKEN_PORT_QNAME,Greeter.class);
updateAddressPort(greeter,test.getPort());
Client client=ClientProxy.getClient(greeter);
Map props=new HashMap();
props.put("action","UsernameToken");
props.put("user","alice");
props.put("passwordType","PasswordText");
WSS4JStaxOutInterceptor wss4jOut=new WSS4JStaxOutInterceptor(props);
client.getOutInterceptors().add(wss4jOut);
((BindingProvider)greeter).getRequestContext().put("password","password");
try {
greeter.greetMe("CXF");
fail("should fail because of password text instead of digest");
}
catch ( Exception ex) {
}
client.getOutInterceptors().remove(wss4jOut);
props.put("passwordType","PasswordDigest");
wss4jOut=new WSS4JStaxOutInterceptor(props);
client.getOutInterceptors().add(wss4jOut);
String s=greeter.greetMe("CXF");
assertEquals("Hello CXF",s);
client.getOutInterceptors().remove(wss4jOut);
try {
((BindingProvider)greeter).getRequestContext().put("password","foo");
wss4jOut=new WSS4JStaxOutInterceptor(props);
client.getOutInterceptors().add(wss4jOut);
greeter.greetMe("CXF");
fail("should fail");
}
catch ( Exception ex) {
}
client.getOutInterceptors().remove(wss4jOut);
try {
props.put("passwordType","PasswordText");
wss4jOut=new WSS4JStaxOutInterceptor(props);
client.getOutInterceptors().add(wss4jOut);
((BindingProvider)greeter).getRequestContext().put("password","password");
greeter.greetMe("CXF");
fail("should fail");
}
catch ( Exception ex) {
}
client.getOutInterceptors().remove(wss4jOut);
((java.io.Closeable)greeter).close();
}
Class: org.apache.cxf.systest.ws.wssc.WSSCTest InternalCallVerifier EqualityVerifier PublicFieldVerifier
@Test public void testSecureConversation() throws Exception {
final wssec.wssc.IPingService port=svc.getPort(new QName("http://WSSec/wssc",test.prefix),wssec.wssc.IPingService.class);
if (PORT2.equals(test.port) || STAX_PORT2.equals(test.port)) {
((BindingProvider)port).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"https://localhost:" + test.port + "/"+ test.prefix);
}
else {
((BindingProvider)port).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"http://localhost:" + test.port + "/"+ test.prefix);
}
if (test.prefix.charAt(0) == '_') {
((BindingProvider)port).getRequestContext().put(SecurityConstants.STS_TOKEN_DO_CANCEL,Boolean.TRUE);
}
if (test.streaming) {
((BindingProvider)port).getRequestContext().put(SecurityConstants.ENABLE_STREAMING_SECURITY,"true");
((BindingProvider)port).getResponseContext().put(SecurityConstants.ENABLE_STREAMING_SECURITY,"true");
}
if (test.clearAction) {
AbstractPhaseInterceptor clearActionInterceptor=new AbstractPhaseInterceptor(Phase.POST_LOGICAL){
public void handleMessage( Message message) throws Fault {
STSClient client=STSUtils.getClient(message,"sct");
client.getOutInterceptors().add(this);
message.put(SecurityConstants.STS_CLIENT,client);
String s=(String)message.get(SoapBindingConstants.SOAP_ACTION);
if (s == null) {
s=SoapActionInInterceptor.getSoapAction(message);
}
if (s != null && s.contains("RST/SCT")) {
message.put(SoapBindingConstants.SOAP_ACTION,"");
}
}
}
;
clearActionInterceptor.addBefore(SoapPreProtocolOutInterceptor.class.getName());
((Client)port).getOutInterceptors().add(clearActionInterceptor);
}
wssec.wssc.PingRequest params=new wssec.wssc.PingRequest();
org.xmlsoap.ping.Ping ping=new org.xmlsoap.ping.Ping();
ping.setOrigin("CXF");
ping.setScenario("Scenario5");
ping.setText("ping");
params.setPing(ping);
try {
wssec.wssc.PingResponse output=port.ping(params);
assertEquals(OUT,output.getPingResponse().getText());
}
catch ( Exception ex) {
throw new Exception("Error doing " + test.prefix,ex);
}
((java.io.Closeable)port).close();
}
Class: org.apache.cxf.systest.ws.wssc.WSSCUnitTest APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testIssueAndRenewUnitTest() throws Exception {
if (test.isStreaming()) {
return;
}
SpringBusFactory bf=new SpringBusFactory();
URL busFile=WSSCUnitTest.class.getResource("client.xml");
Bus bus=bf.createBus(busFile.toString());
SpringBusFactory.setDefaultBus(bus);
SpringBusFactory.setThreadDefaultBus(bus);
STSClient stsClient=new STSClient(bus);
stsClient.setSecureConv(true);
stsClient.setLocation("http://localhost:" + PORT2 + "/"+ "DoubleItSymmetric");
stsClient.setPolicy(createSymmetricBindingPolicy());
Map properties=new HashMap();
properties.put("security.encryption.username","bob");
TokenCallbackHandler callbackHandler=new TokenCallbackHandler();
properties.put("security.callback-handler",callbackHandler);
properties.put("security.signature.properties","alice.properties");
properties.put("security.encryption.properties","bob.properties");
stsClient.setProperties(properties);
SecurityToken securityToken=stsClient.requestSecurityToken("http://localhost:" + PORT2 + "/"+ "DoubleItSymmetric");
assertNotNull(securityToken);
callbackHandler.setSecurityToken(securityToken);
assertNotNull(stsClient.renewSecurityToken(securityToken));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testIssueAndCancelUnitTest() throws Exception {
if (test.isStreaming()) {
return;
}
SpringBusFactory bf=new SpringBusFactory();
URL busFile=WSSCUnitTest.class.getResource("client.xml");
Bus bus=bf.createBus(busFile.toString());
SpringBusFactory.setDefaultBus(bus);
SpringBusFactory.setThreadDefaultBus(bus);
STSClient stsClient=new STSClient(bus);
stsClient.setSecureConv(true);
stsClient.setLocation("http://localhost:" + PORT2 + "/"+ "DoubleItSymmetric");
stsClient.setPolicy(createSymmetricBindingPolicy());
Map properties=new HashMap();
properties.put("security.encryption.username","bob");
TokenCallbackHandler callbackHandler=new TokenCallbackHandler();
properties.put("security.callback-handler",callbackHandler);
properties.put("security.signature.properties","alice.properties");
properties.put("security.encryption.properties","bob.properties");
stsClient.setProperties(properties);
SecurityToken securityToken=stsClient.requestSecurityToken("http://localhost:" + PORT2 + "/"+ "DoubleItSymmetric");
assertNotNull(securityToken);
callbackHandler.setSecurityToken(securityToken);
assertTrue(stsClient.cancelSecurityToken(securityToken));
}
Class: org.apache.cxf.systest.ws.wssec10.WSSecurity10Test InternalCallVerifier EqualityVerifier PublicFieldVerifier
@Test public void testClientServer(){
BusFactory.setDefaultBus(getStaticBus());
BusFactory.setThreadDefaultBus(getStaticBus());
URL wsdlLocation=null;
PingService svc=null;
wsdlLocation=getWsdlLocation(test.prefix,test.port);
svc=new PingService(wsdlLocation);
final IPingService port=svc.getPort(new QName("http://WSSec/wssec10",test.prefix + "_IPingService"),IPingService.class);
Client cl=ClientProxy.getClient(port);
if (test.streaming) {
((BindingProvider)port).getRequestContext().put(SecurityConstants.ENABLE_STREAMING_SECURITY,"true");
((BindingProvider)port).getResponseContext().put(SecurityConstants.ENABLE_STREAMING_SECURITY,"true");
}
HTTPConduit http=(HTTPConduit)cl.getConduit();
HTTPClientPolicy httpClientPolicy=new HTTPClientPolicy();
httpClientPolicy.setConnectionTimeout(0);
httpClientPolicy.setReceiveTimeout(0);
http.setClient(httpClientPolicy);
String output=port.echo(INPUT);
assertEquals(INPUT,output);
cl.destroy();
}
Class: org.apache.cxf.systest.ws.wssec10.WSSecurity10UsernameAuthorizationLegacyTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testClientServerComplexPolicyAuthorized(){
String configName="org/apache/cxf/systest/ws/wssec10/client_restricted.xml";
Bus bus=new SpringBusFactory().createBus(configName);
IPingService port=getComplexPolicyPort(bus);
final String output=port.echo(INPUT);
assertEquals(INPUT,output);
bus.shutdown(true);
}
Class: org.apache.cxf.systest.ws.wssec10.WSSecurity10UsernameAuthorizationTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testClientServerComplexPolicyAuthorized() throws IOException {
String configName="org/apache/cxf/systest/ws/wssec10/client_restricted.xml";
Bus bus=new SpringBusFactory().createBus(configName);
IPingService port=getComplexPolicyPort(bus);
final String output=port.echo(INPUT);
assertEquals(INPUT,output);
((java.io.Closeable)port).close();
bus.shutdown(true);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testClientServerUTOnlyAuthorized() throws IOException {
String configName="org/apache/cxf/systest/ws/wssec10/client_restricted.xml";
Bus bus=new SpringBusFactory().createBus(configName);
IPingService port=getUTOnlyPort(bus,false);
final String output=port.echo(INPUT);
assertEquals(INPUT,output);
((java.io.Closeable)port).close();
bus.shutdown(true);
}
Class: org.apache.cxf.systest.xmlbeans.ClientServerXmlBeansTest UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCallFromClient() throws Exception {
SpringBusFactory factory=new SpringBusFactory();
Bus bus=factory.createBus("org/apache/cxf/systest/xmlbeans/cxf.xml");
BusFactory.setDefaultBus(bus);
URL wsdl=this.getClass().getResource("/wsdl_systest_databinding/xmlbeans/hello_world.wsdl");
assertNotNull("We should have found the WSDL here. ",wsdl);
SOAPService ss=new SOAPService(wsdl,SERVICE_NAME);
Greeter port=ss.getSoapPort();
updateAddressPort(port,WSDL_PORT);
String resp;
ClientProxy.getClient(port).getInInterceptors().add(new LoggingInInterceptor());
ClientProxy.getClient(port).getOutInterceptors().add(new LoggingOutInterceptor());
TestEnum.Enum response=port.sayHiEnum(TestEnum.ONE);
assertEquals(TestEnum.ONE,response);
resp=port.sayHi();
assertEquals("We should get the right response","Bonjour",resp);
resp=port.greetMe("Willem");
assertEquals("We should get the right response","Hello Willem",resp);
String aresp[]=port.sayHiArray(new String[]{"Dan"});
assertEquals("Hello",aresp[0]);
assertEquals("Dan",aresp[1]);
try {
port.greetMe("fault");
fail("Should have been a fault");
}
catch ( GreetMeFault ex) {
assertEquals("Some fault detail",ex.getFaultInfo().getGreetMeFaultDetail());
}
try {
resp=port.greetMe("Invoking greetMe with invalid length string, expecting exception...");
fail("We expect exception here");
}
catch ( WebServiceException ex) {
assertTrue("Get a wrong exception",ex.getMessage().indexOf("string length (67) is greater than maxLength facet (30)") >= 0);
}
try {
port.pingMe();
fail("We expect exception here");
}
catch ( PingMeFault ex) {
FaultDetailDocument detailDocument=ex.getFaultInfo();
FaultDetail detail=detailDocument.getFaultDetail();
assertEquals("Wrong faultDetail major",detail.getMajor(),2);
assertEquals("Wrong faultDetail minor",detail.getMinor(),1);
}
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCallFromDocLitBareClient() throws Exception {
SpringBusFactory factory=new SpringBusFactory();
Bus bus=factory.createBus("org/apache/cxf/systest/xmlbeans/cxf.xml");
BusFactory.setDefaultBus(bus);
URL wsdl=this.getClass().getResource("/wsdl_systest_databinding/xmlbeans/doc_lit_bare.wsdl");
assertNotNull("We should have found the WSDL here. ",wsdl);
org.apache.cxf.xmlbeans.doc_lit_bare.SOAPService ss=new org.apache.cxf.xmlbeans.doc_lit_bare.SOAPService(wsdl,DOC_LIT_BARE_SERVICE);
PutLastTradedPricePortType port=ss.getSoapPort();
updateAddressPort(port,WSDL_PORT);
ClientProxy.getClient(port).getInInterceptors().add(new LoggingInInterceptor());
ClientProxy.getClient(port).getOutInterceptors().add(new LoggingOutInterceptor());
StringRespTypeDocument resp=port.bareNoParam();
assertEquals("Get a wrong response","Get the request!",resp.getStringRespType());
InDecimalDocument xd=InDecimalDocument.Factory.newInstance();
xd.setInDecimal(new BigDecimal(123));
OutStringDocument response=port.nillableParameter(xd);
assertEquals("Get a wrong response","Get the request 123",response.getOutString());
InDocument document=InDocument.Factory.newInstance();
TradePriceData data=document.addNewIn();
data.setTickerPrice(12.33F);
data.setTickerSymbol("CXF");
port.putLastTradedPrice(document);
InoutDocument inOut=InoutDocument.Factory.newInstance();
data=inOut.addNewInout();
data.setTickerPrice(12.33F);
data.setTickerSymbol("CXF");
Holder holder=new Holder(inOut);
port.sayHi(holder);
assertEquals("Get a wrong response","BAK",holder.value.getInout().getTickerSymbol());
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testXmlBeansHeader() throws Exception {
SpringBusFactory factory=new SpringBusFactory();
Bus bus=factory.createBus("org/apache/cxf/systest/xmlbeans/cxf_no_wsdl.xml");
BusFactory.setDefaultBus(bus);
URL wsdl=this.getClass().getResource("/wsdl_systest_databinding/xmlbeans/hello_world.wsdl");
assertNotNull("We should have found the WSDL here. ",wsdl);
SOAPService ss=new SOAPService(wsdl,SERVICE_NAME);
QName soapPort=new QName("http://apache.org/hello_world_soap_http_xmlbeans/xmlbeans","SoapPort");
ss.addPort(soapPort,SOAPBinding.SOAP11HTTP_BINDING,"http://localhost:" + NOWSDL_PORT + "/SoapContext/SoapPort");
Greeter port=ss.getPort(soapPort,Greeter.class);
Client client=ClientProxy.getClient(port);
List headers=new ArrayList();
org.apache.helloWorldSoapHttpXmlbeans.xmlbeans.types.GreetMeDocument doc=org.apache.helloWorldSoapHttpXmlbeans.xmlbeans.types.GreetMeDocument.Factory.newInstance();
doc.addNewGreetMe().setRequestType("doc format header");
Header head=new Header(new QName("","doc"),doc,client.getEndpoint().getService().getDataBinding());
headers.add(head);
org.apache.helloWorldSoapHttpXmlbeans.xmlbeans.types.GreetMeDocument.GreetMe gm=org.apache.helloWorldSoapHttpXmlbeans.xmlbeans.types.GreetMeDocument.GreetMe.Factory.newInstance();
gm.setRequestType("non-doc format header");
head=new Header(new QName("http://somenamespace.com","nondocheader"),gm,client.getEndpoint().getService().getDataBinding());
headers.add(head);
((BindingProvider)port).getRequestContext().put(Header.HEADER_LIST,headers);
String resp;
ClientProxy.getClient(port).getInInterceptors().add(new LoggingInInterceptor());
StringWriter sw=new StringWriter();
PrintWriter pw=new PrintWriter(sw);
ClientProxy.getClient(port).getOutInterceptors().add(new LoggingOutInterceptor(pw));
resp=port.sayHi();
assertEquals("We should get the right response",resp,"Bonjour");
assertTrue(sw.toString().contains("doc format header"));
assertTrue(sw.toString().contains("non-doc format header"));
assertTrue(sw.toString().contains("nondocheader"));
}
UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCallFromClientNoWsdlServer() throws Exception {
SpringBusFactory factory=new SpringBusFactory();
Bus bus=factory.createBus("org/apache/cxf/systest/xmlbeans/cxf_no_wsdl.xml");
BusFactory.setDefaultBus(bus);
URL wsdl=this.getClass().getResource("/wsdl_systest_databinding/xmlbeans/hello_world.wsdl");
assertNotNull("We should have found the WSDL here. ",wsdl);
SOAPService ss=new SOAPService(wsdl,SERVICE_NAME);
QName soapPort=new QName("http://apache.org/hello_world_soap_http_xmlbeans/xmlbeans","SoapPort");
ss.addPort(soapPort,SOAPBinding.SOAP11HTTP_BINDING,"http://localhost:" + NOWSDL_PORT + "/SoapContext/SoapPort");
Greeter port=ss.getPort(soapPort,Greeter.class);
String resp;
ClientProxy.getClient(port).getInInterceptors().add(new LoggingInInterceptor());
ClientProxy.getClient(port).getOutInterceptors().add(new LoggingOutInterceptor());
resp=port.sayHi();
assertEquals("We should get the right response",resp,"Bonjour");
resp=port.greetMe("Willem");
assertEquals("We should get the right response",resp,"Hello Willem");
try {
resp=port.greetMe("Invoking greetMe with invalid length string, expecting exception...");
fail("We expect exception here");
}
catch ( WebServiceException ex) {
assertTrue("Get a wrong exception",ex.getMessage().indexOf("string length (67) is greater than maxLength facet (30)") >= 0);
}
try {
port.pingMe();
fail("We expect exception here");
}
catch ( PingMeFault ex) {
FaultDetailDocument detailDocument=ex.getFaultInfo();
FaultDetail detail=detailDocument.getFaultDetail();
assertEquals("Wrong faultDetail major",detail.getMajor(),2);
assertEquals("Wrong faultDetail minor",detail.getMinor(),1);
}
try {
port.greetMe("fault");
fail("Should have been a fault");
}
catch ( GreetMeFault ex) {
assertEquals("Some fault detail",ex.getFaultInfo().getGreetMeFaultDetail());
}
}
Class: org.apache.cxf.testutil.common.AbstractClientServerTestBase TestCleaner BooleanVerifier InternalCallVerifier HybridVerifier
@AfterClass public static void stopAllServers() throws Exception {
boolean passed=true;
for ( ServerLauncher sl : launchers) {
try {
sl.signalStop();
}
catch ( IOException ex) {
ex.printStackTrace();
}
}
for ( ServerLauncher sl : launchers) {
try {
passed=passed && sl.stopServer();
}
catch ( IOException ex) {
ex.printStackTrace();
}
}
launchers.clear();
System.gc();
assertTrue("server failed",passed);
}
Class: org.apache.cxf.tools.common.ProcessorEnvironmentTest BooleanVerifier InternalCallVerifier
@Test public void testGetBooleanValue(){
Map map=new HashMap();
map.put("k1","true");
ToolContext env=new ToolContext();
env.setParameters(map);
Boolean k1=Boolean.valueOf((String)env.get("k1"));
assertTrue(k1);
Boolean k2=Boolean.valueOf((String)env.get("k2","true"));
assertTrue(k2);
Boolean k3=Boolean.valueOf((String)env.get("k3","yes"));
assertFalse(k3);
}
BooleanVerifier InternalCallVerifier
@Test public void testOptionSet(){
Map map=new HashMap();
map.put("k1","true");
ToolContext env=new ToolContext();
env.setParameters(map);
assertTrue(env.optionSet("k1"));
assertFalse(env.optionSet("k2"));
}
BooleanVerifier InternalCallVerifier
@Test public void testContainsKey(){
Map map=new HashMap();
map.put("k1","v1");
ToolContext env=new ToolContext();
env.setParameters(map);
assertTrue(env.containsKey("k1"));
}
InternalCallVerifier EqualityVerifier
@Test public void testGetDefaultValue(){
Map map=new HashMap();
map.put("k1","v1");
ToolContext env=new ToolContext();
env.setParameters(map);
String k1=(String)env.get("k1","v2");
assertEquals("v1",k1);
String k2=(String)env.get("k2","v2");
assertEquals("v2",k2);
}
InternalCallVerifier EqualityVerifier
@Test public void testPut(){
Map map=new HashMap();
map.put("k1","v1");
ToolContext env=new ToolContext();
env.setParameters(map);
env.put("k2","v2");
String value=(String)env.get("k2");
assertEquals("v2",value);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testRemove(){
Map map=new HashMap();
map.put("k1","v1");
ToolContext env=new ToolContext();
env.setParameters(map);
env.put("k2","v2");
String value=(String)env.get("k2");
assertEquals("v2",value);
env.remove("k1");
assertNull(env.get("k1"));
}
InternalCallVerifier EqualityVerifier
@Test public void testGet(){
Map map=new HashMap();
map.put("k1","v1");
ToolContext env=new ToolContext();
env.setParameters(map);
String value=(String)env.get("k1");
assertEquals("v1",value);
}
Class: org.apache.cxf.tools.common.ToolContextTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetQName() throws Exception {
assertNull(context.getQName(ToolConstants.CFG_SERVICENAME));
context.put(ToolConstants.CFG_SERVICENAME,"SoapService");
QName qname=context.getQName(ToolConstants.CFG_SERVICENAME);
assertEquals(new QName(null,"SoapService"),qname);
qname=context.getQName(ToolConstants.CFG_SERVICENAME,"http://cxf.org");
assertEquals(new QName("http://cxf.org","SoapService"),qname);
context.put(ToolConstants.CFG_SERVICENAME,"http://apache.org=SoapService");
qname=context.getQName(ToolConstants.CFG_SERVICENAME);
assertEquals(new QName("http://apache.org","SoapService"),qname);
}
Class: org.apache.cxf.tools.common.dom.ExtendedDocumentBuilderTest BooleanVerifier InternalCallVerifier
@Test public void testMassMethod() throws Exception {
ExtendedDocumentBuilder builder=new ExtendedDocumentBuilder();
builder.setValidating(false);
String tsSource="/org/apache/cxf/tools/common/toolspec/parser/resources/testtool.xml";
assertTrue(builder.parse(getClass().getResourceAsStream(tsSource)) != null);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testParse() throws Exception {
ExtendedDocumentBuilder builder=new ExtendedDocumentBuilder();
String tsSource="/org/apache/cxf/tools/common/toolspec/parser/resources/testtool1.xml";
Document doc=builder.parse(getClass().getResourceAsStream(tsSource));
assertEquals(doc.getXmlVersion(),"1.0");
}
Class: org.apache.cxf.tools.common.dom.SchemaValidatingSAXParserTest BooleanVerifier InternalCallVerifier
@Test public void testMassMethod(){
SchemaValidatingSAXParser parser=new SchemaValidatingSAXParser();
parser.setValidating(true);
assertTrue(parser.getSAXParser() != null);
}
Class: org.apache.cxf.tools.common.model.JAnnotationTest InternalCallVerifier EqualityVerifier
@Test public void testEnum(){
JAnnotation annotation=new JAnnotation(SOAPBinding.class);
annotation.addElement(new JAnnotationElement("parameterStyle",SOAPBinding.ParameterStyle.BARE));
assertEquals("@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)",annotation.toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testPrimitive(){
JAnnotation annotation=new JAnnotation(WebParam.class);
annotation.addElement(new JAnnotationElement("header",true,true));
annotation.addElement(new JAnnotationElement("mode",Mode.INOUT));
assertEquals("@WebParam(header = true, mode = WebParam.Mode.INOUT)",annotation.toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testList() throws Exception {
JAnnotation annotation=new JAnnotation(XmlSeeAlso.class);
annotation.addElement(new JAnnotationElement(null,Arrays.asList(new Class[]{XmlSeeAlso.class})));
assertEquals("@XmlSeeAlso({XmlSeeAlso.class})",annotation.toString());
assertEquals("javax.xml.bind.annotation.XmlSeeAlso",annotation.getImports().iterator().next());
}
InternalCallVerifier EqualityVerifier
@Test public void testStringForm(){
JAnnotation annotation=new JAnnotation(WebService.class);
annotation.addElement(new JAnnotationElement("name","AddNumbersPortType"));
annotation.addElement(new JAnnotationElement("targetNamespace","http://example.com/"));
assertEquals("@WebService(name = \"AddNumbersPortType\", targetNamespace = \"http://example.com/\")",annotation.toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testAddSame(){
JAnnotation annotation=new JAnnotation(WebParam.class);
annotation.addElement(new JAnnotationElement("header",true,true));
annotation.addElement(new JAnnotationElement("header",false,true));
annotation.addElement(new JAnnotationElement("mode",Mode.INOUT));
annotation.addElement(new JAnnotationElement("mode",Mode.OUT));
assertEquals("@WebParam(header = false, mode = WebParam.Mode.OUT)",annotation.toString());
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testCombination(){
JAnnotation annotation=new JAnnotation(Action.class);
annotation.addElement(new JAnnotationElement("input","3in"));
annotation.addElement(new JAnnotationElement("output","3out"));
JAnnotation faultAction=new JAnnotation(FaultAction.class);
faultAction.addElement(new JAnnotationElement("className",A.class));
faultAction.addElement(new JAnnotationElement("value","3fault"));
annotation.addElement(new JAnnotationElement("fault",Arrays.asList(new JAnnotation[]{faultAction})));
String expected="@Action(input = \"3in\", output = \"3out\", " + "fault = {@FaultAction(className = A.class, value = \"3fault\")})";
assertEquals(expected,annotation.toString());
assertTrue(annotation.getImports().contains("javax.xml.ws.FaultAction"));
assertTrue(annotation.getImports().contains("javax.xml.ws.Action"));
assertTrue(annotation.getImports().contains("org.apache.cxf.tools.common.model.A"));
}
Class: org.apache.cxf.tools.common.model.JavaClassTest InternalCallVerifier EqualityVerifier
@Test public void testGetterSetterStringArray(){
JavaField field=new JavaField("array","String[]","http://doc.withannotation.fortest.tools.cxf.apache.org/");
JavaClass clz=new JavaClass();
clz.setFullClassName("org.apache.cxf.tools.fortest.withannotation.doc.jaxws.SayHi");
JavaMethod getter=clz.appendGetter(field);
assertEquals("getArray",getter.getName());
assertEquals("String[]",getter.getReturn().getClassName());
assertEquals("array",getter.getReturn().getName());
assertEquals("return this.array;",getter.getJavaCodeBlock().getExpressions().get(0).toString());
JavaMethod setter=clz.appendSetter(field);
assertEquals("setArray",setter.getName());
assertEquals("void",setter.getReturn().getClassName());
assertEquals("array",getter.getReturn().getName());
assertEquals("String[]",setter.getParameters().get(0).getClassName());
assertEquals("this.array = newArray;",setter.getJavaCodeBlock().getExpressions().get(0).toString());
field=new JavaField("return","String[]","http://doc.withannotation.fortest.tools.cxf.apache.org/");
clz=new JavaClass();
clz.setFullClassName("org.apache.cxf.tools.fortest.withannotation.doc.jaxws.SayHiResponse");
getter=clz.appendGetter(field);
assertEquals("getReturn",getter.getName());
assertEquals("String[]",getter.getReturn().getClassName());
assertEquals("_return",getter.getReturn().getName());
setter=clz.appendSetter(field);
assertEquals("setReturn",setter.getName());
assertEquals("void",setter.getReturn().getClassName());
assertEquals("_return",getter.getReturn().getName());
assertEquals("String[]",setter.getParameters().get(0).getClassName());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetterSetter() throws Exception {
JavaField field=new JavaField("arg0","org.apache.cxf.tools.fortest.withannotation.doc.TestDataBean","http://doc.withannotation.fortest.tools.cxf.apache.org/");
JavaClass clz=new JavaClass();
clz.setFullClassName("org.apache.cxf.tools.fortest.withannotation.doc.jaxws.EchoDataBean");
JavaMethod getter=clz.appendGetter(field);
assertEquals("getArg0",getter.getName());
assertEquals("org.apache.cxf.tools.fortest.withannotation.doc.TestDataBean",getter.getReturn().getClassName());
assertEquals("arg0",getter.getReturn().getName());
JavaMethod setter=clz.appendSetter(field);
assertEquals("setArg0",setter.getName());
assertEquals("void",setter.getReturn().getClassName());
assertEquals("arg0",getter.getReturn().getName());
assertEquals("org.apache.cxf.tools.fortest.withannotation.doc.TestDataBean",setter.getParameters().get(0).getClassName());
}
Class: org.apache.cxf.tools.common.model.JavaInterfaceTest InternalCallVerifier EqualityVerifier
@Test public void testSetFullClassName() throws Exception {
String fullName="org.apache.cxf.tools.common.model.JavaInterface";
JavaInterface intf=new JavaInterface();
intf.setFullClassName(fullName);
assertEquals("org.apache.cxf.tools.common.model",intf.getPackageName());
assertEquals("JavaInterface",intf.getName());
}
Class: org.apache.cxf.tools.common.model.JavaParameterTest InternalCallVerifier EqualityVerifier
@Test public void testGetHolderDefaultTypeValue() throws Exception {
JavaParameter holderParameter=new JavaParameter("i","java.lang.String",null);
holderParameter.setHolder(true);
holderParameter.setHolderName("javax.xml.ws.Holder");
assertEquals("\"\"",holderParameter.getDefaultTypeValue());
holderParameter=new JavaParameter("org.apache.cxf.tools.common.model.JavaParameter","org.apache.cxf.tools.common.model.JavaParameter",null);
holderParameter.setHolder(true);
holderParameter.setHolderName("javax.xml.ws.Holder");
String defaultTypeValue=holderParameter.getDefaultTypeValue();
assertEquals("new org.apache.cxf.tools.common.model.JavaParameter()",defaultTypeValue);
}
Class: org.apache.cxf.tools.common.model.JavaTypeTest InternalCallVerifier EqualityVerifier
@Test public void testSetClass(){
JavaType type=new JavaType();
type.setClassName("foo.bar.A");
assertEquals("foo.bar",type.getPackageName());
assertEquals("A",type.getSimpleName());
}
Class: org.apache.cxf.tools.common.toolspec.AbstractToolContainerTest InternalCallVerifier NullVerifier
@Test public void testQuietMode(){
try {
dummyTool.setArguments(new String[]{"-q"});
dummyTool.parseCommandLine();
}
catch ( Exception e) {
}
assertNotNull("Fail to redirect err output:",dummyTool.getErrOutputStream());
assertNotNull("Fail to redirect output:",dummyTool.getOutOutputStream());
}
Class: org.apache.cxf.tools.common.toolspec.ToolExceptionTest BooleanVerifier InternalCallVerifier
@Test public void testMassMethod(){
ToolException e=new ToolException("e");
assertTrue(e.getCause() == null);
e=new ToolException("run time exception",new RuntimeException("test run time exception"));
assertTrue(e.getCause() instanceof RuntimeException);
assertTrue(e.toString() != null);
}
Class: org.apache.cxf.tools.common.toolspec.ToolSpecTest APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testGetHandler() throws Exception {
String tsSource="parser/resources/testtool1.xml";
toolSpec=new ToolSpec(getClass().getResourceAsStream(tsSource),false);
assertNotNull(toolSpec.getHandler());
assertNotNull(toolSpec.getHandler(this.getClass().getClassLoader()));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testGetParameterDefault() throws Exception {
String tsSource="parser/resources/testtool.xml";
toolSpec=new ToolSpec(getClass().getResourceAsStream(tsSource),false);
assertTrue(toolSpec.getAnnotation() == null);
assertTrue(toolSpec.getParameterDefault("namespace") == null);
assertTrue(toolSpec.getParameterDefault("wsdlurl") == null);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testIsValidInputStream() throws Exception {
String tsSource="parser/resources/testtool1.xml";
toolSpec=new ToolSpec(getClass().getResourceAsStream(tsSource),false);
assertTrue(toolSpec.isValidInputStream("testID"));
assertTrue(!toolSpec.isValidInputStream("dummyID"));
assertTrue(toolSpec.getInstreamIds().size() == 1);
}
Class: org.apache.cxf.tools.common.toolspec.parser.CommandLineParserTest UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testInvalidPackageName(){
try {
String[] args=new String[]{"-p","/test","arg1"};
parser.parseArguments(args);
fail("testInvalidPackageName failed");
}
catch ( BadUsageException ex) {
Object[] errors=ex.getErrors().toArray();
assertEquals("testInvalidPackageName failed",1,errors.length);
CommandLineError error=(CommandLineError)errors[0];
assertTrue("Expected InvalidArgumentValue error",error instanceof ErrorVisitor.UserError);
ErrorVisitor.UserError userError=(ErrorVisitor.UserError)error;
assertEquals("Invalid argument value message incorrect","-p has invalid character!",userError.toString());
}
}
APIUtilityVerifier IterativeVerifier BranchVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testFormattedDetailedUsage() throws Exception {
String usage=parser.getFormattedDetailedUsage();
assertNotNull(usage);
StringTokenizer st1=new StringTokenizer(usage,System.getProperty("line.separator"));
assertEquals(14,st1.countTokens());
while (st1.hasMoreTokens()) {
String s=st1.nextToken();
if (s.indexOf("java package") != -1) {
s=s.trim();
assertTrue(s.charAt(s.length() - 1) != 'o');
}
else if (s.indexOf("impl - the") != -1) {
assertTrue(s.charAt(s.length() - 1) == 'o');
}
}
}
BooleanVerifier InternalCallVerifier
@Test public void testOtherMethods() throws Exception {
String tsSource="/org/apache/cxf/tools/common/toolspec/parser/resources/testtool.xml";
ToolSpec toolspec=new ToolSpec(getClass().getResourceAsStream(tsSource),false);
CommandLineParser commandLineParser=new CommandLineParser(null);
commandLineParser.setToolSpec(toolspec);
CommandDocument commandDocument=commandLineParser.parseArguments("-r unknown");
assertTrue(commandDocument != null);
}
IterativeVerifier InternalCallVerifier EqualityVerifier
@Test public void testDetailedUsage() throws Exception {
String specialItem="[ -p <[wsdl namespace =]Package Name> ]*";
if (!isQuolifiedVersion()) {
specialItem="-p <[wsdl namespace =]Package Name>*";
}
String[] expected=new String[]{"[ -n ]","Namespace","[ -impl ]","impl - the impl that will be used by this tool to do " + "whatever it is this tool does.","[ -e ]","enum","-r","required",specialItem,"The java package name to use for the generated code." + "Also, optionally specify the wsdl namespace mapping to " + "a particular java packagename.","[ -? ]","help","[ -v ]","version","","WSDL/SCHEMA URL"};
int index=0;
String lineSeparator=System.getProperty("line.separator");
StringTokenizer st1=new StringTokenizer(parser.getDetailedUsage(),lineSeparator);
while (st1.hasMoreTokens()) {
assertEquals("Failed at line " + index,expected[index++],st1.nextToken().toString().trim());
}
}
UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testUnexpectedOption(){
try {
String[] args=new String[]{"-n","test","-r","-unknown"};
parser.parseArguments(args);
fail("testUnexpectedOption failed");
}
catch ( BadUsageException ex) {
Object[] errors=ex.getErrors().toArray();
assertEquals("testInvalidOption failed",1,errors.length);
CommandLineError error=(CommandLineError)errors[0];
assertTrue("Expected UnexpectedOption error",error instanceof ErrorVisitor.UnexpectedOption);
ErrorVisitor.UnexpectedOption option=(ErrorVisitor.UnexpectedOption)error;
assertEquals("UnexpectedOption incorrect","-unknown",option.getOptionSwitch());
}
}
InternalCallVerifier EqualityVerifier
@Test public void testValidArgumentEnumValue() throws Exception {
String[] args=new String[]{"-r","-e","true","arg1"};
CommandDocument result=parser.parseArguments(args);
assertEquals("testValidArguments Failed","true",result.getParameter("enum"));
}
UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testInvalidArgumentEnumValue() throws Exception {
try {
String[] args=new String[]{"-e","wrongvalue"};
parser.parseArguments(args);
fail("testInvalidArgumentEnumValue failed");
}
catch ( BadUsageException ex) {
Object[] errors=ex.getErrors().toArray();
assertEquals("testInvalidArgumentEnumValu failed",1,errors.length);
CommandLineError error=(CommandLineError)errors[0];
assertTrue("Expected InvalidArgumentEnumValu error",error instanceof ErrorVisitor.UserError);
ErrorVisitor.UserError userError=(ErrorVisitor.UserError)error;
assertEquals("Invalid enum argument value message incorrect","-e wrongvalue not in the enumeration value list!",userError.toString());
}
}
BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testUsage() throws Exception {
String usage="[ -n ] [ -impl ] [ -e ] -r " + "[ -p <[wsdl namespace =]Package Name> ]* [ -? ] [ -v ] ";
String pUsage=parser.getUsage();
if (isQuolifiedVersion()) {
assertEquals("This test failed in the xerces version above 2.7.1 or the version with JDK ",usage,pUsage);
}
else {
usage="[ -n ] [ -impl ] [ -e ] -r " + "-p <[wsdl namespace =]Package Name>* [ -? ] [ -v ] ";
assertEquals("This test failed in the xerces version below 2.7.1",usage.trim(),pUsage.trim());
}
}
UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testMissingArgument(){
try {
String[] args=new String[]{"-n","test","-r"};
parser.parseArguments(args);
fail("testMissingArgument failed");
}
catch ( BadUsageException ex) {
Object[] errors=ex.getErrors().toArray();
assertEquals("testInvalidOption failed",1,errors.length);
CommandLineError error=(CommandLineError)errors[0];
assertTrue("Expected MissingArgument error",error instanceof ErrorVisitor.MissingArgument);
ErrorVisitor.MissingArgument arg=(ErrorVisitor.MissingArgument)error;
assertEquals("MissingArgument incorrect","wsdlurl",arg.getArgument());
}
}
UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testInvalidOption(){
try {
String[] args=new String[]{"-n","-r","arg1"};
parser.parseArguments(args);
fail("testInvalidOption failed");
}
catch ( BadUsageException ex) {
Object[] errors=ex.getErrors().toArray();
assertEquals("testInvalidOption failed",1,errors.length);
CommandLineError error=(CommandLineError)errors[0];
assertTrue("Expected InvalidOption error",error instanceof ErrorVisitor.InvalidOption);
ErrorVisitor.InvalidOption option=(ErrorVisitor.InvalidOption)error;
assertEquals("Invalid option incorrect","-n",option.getOptionSwitch());
assertEquals("Invalid option message incorrect","Invalid option: -n is missing its associated argument",option.toString());
}
}
InternalCallVerifier EqualityVerifier
@Test public void testValidArguments() throws Exception {
String[] args=new String[]{"-r","-n","test","arg1"};
CommandDocument result=parser.parseArguments(args);
assertEquals("testValidArguments Failed","test",result.getParameter("namespace"));
}
UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testDuplicateArgument(){
try {
String[] args=new String[]{"-n","test","-r","arg1","arg2"};
parser.parseArguments(args);
fail("testUnexpectedArgument failed");
}
catch ( BadUsageException ex) {
Object[] errors=ex.getErrors().toArray();
assertEquals("testInvalidOption failed",1,errors.length);
CommandLineError error=(CommandLineError)errors[0];
assertTrue("Expected UnexpectedArgument error",error instanceof ErrorVisitor.UnexpectedArgument);
}
}
UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testMissingOption(){
try {
String[] args=new String[]{"-n","test","arg1"};
parser.parseArguments(args);
fail("testMissingOption failed");
}
catch ( BadUsageException ex) {
Object[] errors=ex.getErrors().toArray();
assertEquals("testInvalidOption failed",1,errors.length);
CommandLineError error=(CommandLineError)errors[0];
assertTrue("Expected MissingOption error",error instanceof ErrorVisitor.MissingOption);
ErrorVisitor.MissingOption option=(ErrorVisitor.MissingOption)error;
assertEquals("Missing option incorrect","r",option.getOptionSwitch());
}
}
UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testInvalidArgumentValue() throws Exception {
try {
String[] args=new String[]{"-n","test@","arg1"};
parser.parseArguments(args);
fail("testInvalidArgumentValue failed");
}
catch ( BadUsageException ex) {
Object[] errors=ex.getErrors().toArray();
assertEquals("testInvalidArgumentValue failed",1,errors.length);
CommandLineError error=(CommandLineError)errors[0];
assertTrue("Expected InvalidArgumentValue error",error instanceof ErrorVisitor.UserError);
ErrorVisitor.UserError userError=(ErrorVisitor.UserError)error;
assertEquals("Invalid argument value message incorrect","-n has invalid character!",userError.toString());
}
}
InternalCallVerifier EqualityVerifier
@Test public void testvalidPackageName() throws Exception {
String[] args=new String[]{"-p","http://www.iona.com/hello_world_soap_http=com.iona","-r","arg1"};
CommandDocument result=parser.parseArguments(args);
assertEquals("testValidPackageName Failed","http://www.iona.com/hello_world_soap_http=com.iona",result.getParameter("packagename"));
}
InternalCallVerifier EqualityVerifier
@Test public void testValidMixedArguments() throws Exception {
String[] args=new String[]{"-v","-r","-n","test","arg1"};
CommandDocument result=parser.parseArguments(args);
assertEquals("testValidMissedArguments Failed","test",result.getParameter("namespace"));
}
Class: org.apache.cxf.tools.corba.processors.IDLToWSDLGenerationTest BranchVerifier InternalCallVerifier EqualityVerifier
@Test public void testEncodingGeneration() throws Exception {
try {
String sourceIdlFilename="/idl/Enum.idl";
URL idl=getClass().getResource(sourceIdlFilename);
ProcessorEnvironment env=new ProcessorEnvironment();
Map cfg=new HashMap();
cfg.put(ToolCorbaConstants.CFG_IDLFILE,new File(idl.toURI()).getAbsolutePath());
cfg.put(ToolCorbaConstants.CFG_WSDL_ENCODING,"UTF-16");
env.setParameters(cfg);
IDLToWSDLProcessor processor=new IDLToWSDLProcessor();
processor.setEnvironment(env);
Writer out=processor.getOutputWriter("Enum.wsdl",".");
if (out instanceof OutputStreamWriter) {
OutputStreamWriter writer=(OutputStreamWriter)out;
assertEquals("Encoding should be UTF-16",writer.getEncoding(),"UTF-16");
}
out.close();
}
finally {
new File("Enum.wsdl").deleteOnExit();
}
}
Class: org.apache.cxf.tools.corba.processors.WSDLToCorbaBindingTest APIUtilityVerifier IterativeVerifier BranchVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testArrayMapping() throws Exception {
try {
String fileName=getClass().getResource("/wsdl/array.wsdl").toString();
generator.setWsdlFile(fileName);
generator.addInterfaceName("X");
Definition model=generator.generateCORBABinding();
QName bName=new QName("http://schemas.apache.org/idl/anon.idl","XCORBABinding","tns");
Binding binding=model.getBinding(bName);
assertNotNull(binding);
assertEquals("XCORBABinding",binding.getQName().getLocalPart());
assertEquals("X",binding.getPortType().getQName().getLocalPart());
assertEquals(1,binding.getExtensibilityElements().size());
assertEquals(1,binding.getBindingOperations().size());
for ( ExtensibilityElement extElement : getExtensibilityElements(binding)) {
if (extElement.getElementType().getLocalPart().equals("binding")) {
BindingType bindingType=(BindingType)extElement;
assertEquals(bindingType.getRepositoryID(),"IDL:X:1.0");
}
}
Iterator> j=binding.getBindingOperations().iterator();
while (j.hasNext()) {
BindingOperation bindingOperation=(BindingOperation)j.next();
assertEquals(1,bindingOperation.getExtensibilityElements().size());
assertEquals(bindingOperation.getBindingInput().getName(),"op_a");
assertEquals(bindingOperation.getBindingOutput().getName(),"op_aResponse");
for ( ExtensibilityElement extElement : getExtensibilityElements(bindingOperation)) {
if (extElement.getElementType().getLocalPart().equals("operation")) {
OperationType corbaOpType=(OperationType)extElement;
assertEquals(corbaOpType.getName(),"op_a");
assertEquals(1,corbaOpType.getParam().size());
assertNotNull(corbaOpType.getReturn());
ParamType paramtype=corbaOpType.getParam().get(0);
assertEquals(paramtype.getName(),"part1");
QName idltype=new QName("http://schemas.apache.org/idl/anon.idl/corba/typemap/","ArrayType","ns1");
assertEquals(paramtype.getIdltype(),idltype);
assertEquals(paramtype.getMode().toString(),"IN");
}
}
}
WSDLToIDLAction idlgen=new WSDLToIDLAction();
idlgen.setBindingName("XCORBABinding");
idlgen.setOutputFile("array.idl");
idlgen.generateIDL(model);
File f=new File("array.idl");
assertTrue("array.idl should be generated",f.exists());
}
finally {
new File("array.idl").deleteOnExit();
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testUnionType() throws Exception {
try {
String fileName=getClass().getResource("/wsdl/uniontype.wsdl").toString();
generator.setWsdlFile(fileName);
generator.addInterfaceName("Test.MultiPart");
Definition model=generator.generateCORBABinding();
Document document=writer.getDocument(model);
Element typemap=getElementNode(document,"corba:typeMapping");
assertNotNull(typemap);
assertEquals(1,typemap.getElementsByTagName("corba:union").getLength());
assertEquals(1,typemap.getElementsByTagName("corba:enum").getLength());
WSDLToIDLAction idlgen=new WSDLToIDLAction();
idlgen.setBindingName("Test.MultiPartCORBABinding");
idlgen.setOutputFile("uniontype.idl");
idlgen.generateIDL(model);
File f=new File("uniontype.idl");
assertTrue("uniontype.idl should be generated",f.exists());
}
finally {
new File("uniontype.idl").deleteOnExit();
}
}
APIUtilityVerifier IterativeVerifier BranchVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testMixedArraysMapping() throws Exception {
try {
String fileName=getClass().getResource("/wsdl/arrays-mixed.wsdl").toString();
generator.setWsdlFile(fileName);
generator.addInterfaceName("X");
Definition model=generator.generateCORBABinding();
QName bName=new QName("http://schemas.apache.org/idl/anon.idl","XCORBABinding","tns");
Binding binding=model.getBinding(bName);
assertNotNull(binding);
assertEquals("XCORBABinding",binding.getQName().getLocalPart());
assertEquals("X",binding.getPortType().getQName().getLocalPart());
assertEquals(1,binding.getExtensibilityElements().size());
assertEquals(1,binding.getBindingOperations().size());
for ( ExtensibilityElement extElement : getExtensibilityElements(binding)) {
if (extElement.getElementType().getLocalPart().equals("binding")) {
BindingType bindingType=(BindingType)extElement;
assertEquals(bindingType.getRepositoryID(),"IDL:X:1.0");
}
}
Iterator> tm=model.getExtensibilityElements().iterator();
assertTrue(tm.hasNext());
TypeMappingType tmt=(TypeMappingType)tm.next();
CorbaTypeMap typeMap=CorbaUtils.createCorbaTypeMap(Arrays.asList(tmt));
assertNull("All nested anonymous types should have \"nested\" names",typeMap.getType("item"));
assertMixedArraysMappingEasyTypes(typeMap);
assertMixedArraysMappingDifficultSequences(typeMap);
assertMixedArraysMappingDifficultArrays(typeMap);
Iterator> j=binding.getBindingOperations().iterator();
while (j.hasNext()) {
BindingOperation bindingOperation=(BindingOperation)j.next();
assertEquals(1,bindingOperation.getExtensibilityElements().size());
assertEquals(bindingOperation.getBindingInput().getName(),"op_a");
assertEquals(bindingOperation.getBindingOutput().getName(),"op_aResponse");
for ( ExtensibilityElement extElement : getExtensibilityElements(bindingOperation)) {
if (extElement.getElementType().getLocalPart().equals("operation")) {
OperationType corbaOpType=(OperationType)extElement;
assertEquals(corbaOpType.getName(),"op_a");
assertEquals(1,corbaOpType.getParam().size());
assertNotNull(corbaOpType.getReturn());
ParamType paramtype=corbaOpType.getParam().get(0);
assertEquals(paramtype.getName(),"part1");
QName idltype=new QName("http://schemas.apache.org/idl/anon.idl/corba/typemap/","MixedArrayType","ns1");
assertEquals(paramtype.getIdltype(),idltype);
assertEquals(paramtype.getMode().toString(),"IN");
}
else if (extElement.getElementType().getLocalPart().equals("typeMapping")) {
System.out.println("x");
}
}
}
WSDLToIDLAction idlgen=new WSDLToIDLAction();
idlgen.setBindingName("XCORBABinding");
idlgen.setOutputFile("array.idl");
idlgen.generateIDL(model);
File f=new File("array.idl");
assertTrue("array.idl should be generated",f.exists());
}
finally {
new File("array.idl").deleteOnExit();
}
}
APIUtilityVerifier IterativeVerifier InternalCallVerifier EqualityVerifier
@Test public void testFixedBindingGeneration() throws Exception {
String fileName=getClass().getResource("/wsdl/fixed.wsdl").toString();
generator.setWsdlFile(fileName);
generator.addInterfaceName("Y");
Definition model=generator.generateCORBABinding();
Document document=writer.getDocument(model);
Element typemap=getElementNode(document,"corba:typeMapping");
assertEquals(1,typemap.getElementsByTagName("corba:sequence").getLength());
assertEquals(5,typemap.getElementsByTagName("corba:fixed").getLength());
Element bindingElement=getElementNode(document,"binding");
assertEquals(5,bindingElement.getElementsByTagName("corba:operation").getLength());
QName bName=new QName("http://schemas.apache.org/idl/fixed.idl","YCORBABinding","tns");
Binding binding=model.getBinding(bName);
TypeMappingType mapType=(TypeMappingType)model.getExtensibilityElements().get(0);
Map tmap=new HashMap();
for ( CorbaType type : mapType.getStructOrExceptionOrUnion()) {
tmap.put(type.getName(),type);
}
Iterator> j=binding.getBindingOperations().iterator();
while (j.hasNext()) {
BindingOperation bindingOperation=(BindingOperation)j.next();
assertEquals("YCORBABinding",binding.getQName().getLocalPart());
assertEquals(1,bindingOperation.getExtensibilityElements().size());
checkFixedTypeOne(bindingOperation,tmap);
bindingOperation=(BindingOperation)j.next();
checkSequenceType(bindingOperation,tmap);
bindingOperation=(BindingOperation)j.next();
checkFixedTypeTwo(bindingOperation,tmap);
bindingOperation=(BindingOperation)j.next();
checkFixedTypeThree(bindingOperation,tmap);
bindingOperation=(BindingOperation)j.next();
checkFixedTypeFour(bindingOperation,tmap);
}
}
APIUtilityVerifier BranchVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testMultipartCORBABindingGeneration() throws Exception {
String fileName=getClass().getResource("/wsdl/multipart.wsdl").toString();
generator.setWsdlFile(fileName);
generator.addInterfaceName("Test.MultiPart");
Definition model=generator.generateCORBABinding();
QName bName=new QName("http://schemas.apache.org/tests","Test.MultiPartCORBABinding","tns");
Binding binding=model.getBinding(bName);
assertNotNull(binding);
assertEquals("Test.MultiPartCORBABinding",binding.getQName().getLocalPart());
assertEquals("Test.MultiPart",binding.getPortType().getQName().getLocalPart());
assertEquals(1,binding.getExtensibilityElements().size());
assertEquals(32,binding.getBindingOperations().size());
List extElements=getExtensibilityElements(binding);
ExtensibilityElement extElement=extElements.get(0);
if (extElement.getElementType().getLocalPart().equals("binding")) {
BindingType bindingType=(BindingType)extElement;
assertEquals(bindingType.getRepositoryID(),"IDL:Test/MultiPart:1.0");
}
getStringAttributeTest(binding);
getTestIdTest(binding);
setTestIdTest(binding);
testVoidTest(binding);
testPrimitiveTypeTest(binding,"test_short",CorbaConstants.NT_CORBA_SHORT);
testPrimitiveTypeTest(binding,"test_long",CorbaConstants.NT_CORBA_LONG);
testPrimitiveTypeTest(binding,"test_longlong",CorbaConstants.NT_CORBA_LONGLONG);
testPrimitiveTypeTest(binding,"test_ushort",CorbaConstants.NT_CORBA_USHORT);
testPrimitiveTypeTest(binding,"test_ulong",CorbaConstants.NT_CORBA_ULONG);
testPrimitiveTypeTest(binding,"test_ulonglong",CorbaConstants.NT_CORBA_ULONGLONG);
testPrimitiveTypeTest(binding,"test_float",CorbaConstants.NT_CORBA_FLOAT);
testPrimitiveTypeTest(binding,"test_double",CorbaConstants.NT_CORBA_DOUBLE);
testPrimitiveTypeTest(binding,"test_octet",CorbaConstants.NT_CORBA_OCTET);
testPrimitiveTypeTest(binding,"test_boolean",CorbaConstants.NT_CORBA_BOOLEAN);
testPrimitiveTypeTest(binding,"test_char",CorbaConstants.NT_CORBA_CHAR);
testPrimitiveTypeTest(binding,"test_integer",CorbaConstants.NT_CORBA_LONGLONG);
testPrimitiveTypeTest(binding,"test_nonNegativeInteger",CorbaConstants.NT_CORBA_ULONGLONG);
testPrimitiveTypeTest(binding,"test_positiveInteger",CorbaConstants.NT_CORBA_ULONGLONG);
testPrimitiveTypeTest(binding,"test_negativeInteger",CorbaConstants.NT_CORBA_LONGLONG);
testPrimitiveTypeTest(binding,"test_normalizedString",CorbaConstants.NT_CORBA_STRING);
testPrimitiveTypeTest(binding,"test_token",CorbaConstants.NT_CORBA_STRING);
testPrimitiveTypeTest(binding,"test_language",CorbaConstants.NT_CORBA_STRING);
testPrimitiveTypeTest(binding,"test_Name",CorbaConstants.NT_CORBA_STRING);
testPrimitiveTypeTest(binding,"test_NCName",CorbaConstants.NT_CORBA_STRING);
testPrimitiveTypeTest(binding,"test_ID",CorbaConstants.NT_CORBA_STRING);
testPrimitiveTypeTest(binding,"test_anyURI",CorbaConstants.NT_CORBA_STRING);
testPrimitiveTypeTest(binding,"test_nick_name",CorbaConstants.NT_CORBA_STRING);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testMultipartTypeMapGeneration() throws Exception {
String fileName=getClass().getResource("/wsdl/multipart.wsdl").toString();
generator.setWsdlFile(fileName);
generator.addInterfaceName("Test.MultiPart");
Definition model=generator.generateCORBABinding();
Document document=writer.getDocument(model);
Element typemap=getElementNode(document,"corba:typeMapping");
assertNotNull(typemap);
assertEquals(1,typemap.getElementsByTagName("corba:enum").getLength());
}
APIUtilityVerifier IterativeVerifier BranchVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCORBABindingGeneration() throws Exception {
String fileName=getClass().getResource("/wsdl/simpleList.wsdl").toString();
generator.setWsdlFile(fileName);
generator.addInterfaceName("BasePortType");
Definition model=generator.generateCORBABinding();
QName bName=new QName("http://schemas.apache.org/tests","BaseCORBABinding","tns");
Binding binding=model.getBinding(bName);
assertNotNull(binding);
assertEquals("BaseCORBABinding",binding.getQName().getLocalPart());
assertEquals("BasePortType",binding.getPortType().getQName().getLocalPart());
assertEquals(1,binding.getExtensibilityElements().size());
assertEquals(1,binding.getBindingOperations().size());
for ( ExtensibilityElement extElement : getExtensibilityElements(binding)) {
if (extElement.getElementType().getLocalPart().equals("binding")) {
BindingType bindingType=(BindingType)extElement;
assertEquals(bindingType.getRepositoryID(),"IDL:BasePortType:1.0");
}
}
Iterator> j=binding.getBindingOperations().iterator();
while (j.hasNext()) {
BindingOperation bindingOperation=(BindingOperation)j.next();
assertEquals(1,bindingOperation.getExtensibilityElements().size());
assertEquals(bindingOperation.getBindingInput().getName(),"echoString");
assertEquals(bindingOperation.getBindingOutput().getName(),"echoStringResponse");
for ( ExtensibilityElement extElement : getExtensibilityElements(bindingOperation)) {
if (extElement.getElementType().getLocalPart().equals("operation")) {
OperationType corbaOpType=(OperationType)extElement;
assertEquals(corbaOpType.getName(),"echoString");
assertEquals(3,corbaOpType.getParam().size());
assertEquals(corbaOpType.getReturn().getName(),"return");
assertEquals(corbaOpType.getReturn().getIdltype(),CorbaConstants.NT_CORBA_STRING);
assertEquals(corbaOpType.getParam().get(0).getName(),"x");
assertEquals(corbaOpType.getParam().get(0).getMode().value(),"in");
QName qname=new QName("http://schemas.apache.org/tests/corba/typemap/","StringEnum1","ns1");
assertEquals(corbaOpType.getParam().get(0).getIdltype(),qname);
}
}
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testAllType() throws Exception {
try {
String fileName=getClass().getResource("/wsdl/alltype.wsdl").toString();
generator.setWsdlFile(fileName);
generator.addInterfaceName("BasePortType");
Definition model=generator.generateCORBABinding();
Document document=writer.getDocument(model);
Element typemap=getElementNode(document,"corba:typeMapping");
assertEquals(1,typemap.getElementsByTagName("corba:struct").getLength());
WSDLToIDLAction idlgen=new WSDLToIDLAction();
idlgen.setBindingName("BaseCORBABinding");
idlgen.setOutputFile("alltype.idl");
idlgen.generateIDL(model);
File f=new File("alltype.idl");
assertTrue("alltype.idl should be generated",f.exists());
}
finally {
new File("alltype.idl").deleteOnExit();
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSequenceType() throws Exception {
try {
String fileName=getClass().getResource("/wsdl/sequencetype.wsdl").toString();
generator.setWsdlFile(fileName);
generator.addInterfaceName("IACC.Server");
Definition model=generator.generateCORBABinding();
Document document=writer.getDocument(model);
Element typemap=getElementNode(document,"corba:typeMapping");
assertNotNull(typemap);
assertEquals(2,typemap.getElementsByTagName("corba:sequence").getLength());
assertEquals(5,typemap.getElementsByTagName("corba:exception").getLength());
assertEquals(70,typemap.getElementsByTagName("corba:struct").getLength());
WSDLToIDLAction idlgen=new WSDLToIDLAction();
idlgen.setBindingName("IACC.ServerCORBABinding");
idlgen.setOutputFile("sequencetype.idl");
idlgen.generateIDL(model);
File f=new File("sequencetype.idl");
assertTrue("sequencetype.idl should be generated",f.exists());
}
finally {
new File("sequencetype.idl").deleteOnExit();
}
}
APIUtilityVerifier IterativeVerifier BranchVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testExceptionCORBABindingGeneration() throws Exception {
String fileName=getClass().getResource("/wsdl/exceptions.wsdl").toString();
generator.setWsdlFile(fileName);
generator.addInterfaceName("TestException.ExceptionTest");
Definition model=generator.generateCORBABinding();
QName bName=new QName("http://schemas.apache.org/idl/exceptions.idl","TestException.ExceptionTestCORBABinding","tns");
Binding binding=model.getBinding(bName);
assertNotNull(binding);
assertEquals("TestException.ExceptionTestCORBABinding",binding.getQName().getLocalPart());
assertEquals("TestException.ExceptionTest",binding.getPortType().getQName().getLocalPart());
assertEquals(1,binding.getExtensibilityElements().size());
assertEquals(1,binding.getBindingOperations().size());
for ( ExtensibilityElement extElement : getExtensibilityElements(binding)) {
if (extElement.getElementType().getLocalPart().equals("binding")) {
BindingType bindingType=(BindingType)extElement;
assertEquals(bindingType.getRepositoryID(),"IDL:TestException/ExceptionTest:1.0");
}
}
Iterator> j=binding.getBindingOperations().iterator();
while (j.hasNext()) {
BindingOperation bindingOperation=(BindingOperation)j.next();
assertEquals(1,bindingOperation.getExtensibilityElements().size());
assertEquals(bindingOperation.getBindingInput().getName(),"review_data");
assertEquals(bindingOperation.getBindingOutput().getName(),"review_dataResponse");
Iterator> f=bindingOperation.getBindingFaults().values().iterator();
boolean hasBadRecord=false;
boolean hasMyException=false;
while (f.hasNext()) {
BindingFault bindingFault=(BindingFault)f.next();
if ("TestException.BadRecord".equals(bindingFault.getName())) {
hasBadRecord=true;
}
else if ("MyException".equals(bindingFault.getName())) {
hasMyException=true;
}
else {
fail("Unexpected BindingFault: " + bindingFault.getName());
}
}
assertTrue("Did not get expected TestException.BadRecord",hasBadRecord);
assertTrue("Did not get expected MyException",hasMyException);
for ( ExtensibilityElement extElement : getExtensibilityElements(bindingOperation)) {
if (extElement.getElementType().getLocalPart().equals("operation")) {
OperationType corbaOpType=(OperationType)extElement;
assertEquals(corbaOpType.getName(),"review_data");
assertEquals(1,corbaOpType.getParam().size());
assertEquals(2,corbaOpType.getRaises().size());
hasBadRecord=false;
hasMyException=false;
for (int k=0; k < corbaOpType.getRaises().size(); k++) {
String localPart=corbaOpType.getRaises().get(k).getException().getLocalPart();
if ("TestException.BadRecord".equals(localPart)) {
hasBadRecord=true;
}
else if ("MyExceptionType".equals(localPart)) {
hasMyException=true;
}
else {
fail("Unexpected Raises: " + localPart);
}
}
assertTrue("Did not find expected TestException.BadRecord",hasBadRecord);
assertTrue("Did not find expected MyException",hasMyException);
}
}
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCORBATypeMapGeneration() throws Exception {
String fileName=getClass().getResource("/wsdl/simpleList.wsdl").toString();
generator.setWsdlFile(fileName);
generator.addInterfaceName("BasePortType");
Definition model=generator.generateCORBABinding();
Document document=writer.getDocument(model);
Element typemap=getElementNode(document,"corba:typeMapping");
assertNotNull(typemap);
assertEquals(2,typemap.getElementsByTagName("corba:sequence").getLength());
assertEquals(1,typemap.getElementsByTagName("corba:enum").getLength());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testComplexContentStructType() throws Exception {
try {
String fileName=getClass().getResource("/wsdl/content.wsdl").toString();
generator.setWsdlFile(fileName);
generator.addInterfaceName("ContentPortType");
Definition model=generator.generateCORBABinding();
Document document=writer.getDocument(model);
Element typemap=getElementNode(document,"corba:typeMapping");
assertEquals(1,typemap.getElementsByTagName("corba:union").getLength());
assertEquals(6,typemap.getElementsByTagName("corba:struct").getLength());
WSDLToIDLAction idlgen=new WSDLToIDLAction();
idlgen.setBindingName("ContentCORBABinding");
idlgen.setOutputFile("content.idl");
idlgen.generateIDL(model);
File f=new File("content.idl");
assertTrue("content.idl should be generated",f.exists());
}
finally {
new File("content.idl").deleteOnExit();
}
}
Class: org.apache.cxf.tools.corba.processors.WSDLToCorbaBindingTypeTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testNestedDerivedTypes() throws Exception {
try {
String fileName=getClass().getResource("/wsdl/nested-derivedtypes.wsdl").toString();
generator.setWsdlFile(fileName);
generator.addInterfaceName("DerivedTypesPortType");
Definition model=generator.generateCORBABinding();
Document document=writer.getDocument(model);
Element typemap=getElementNode(document,"corba:typeMapping");
assertNotNull(typemap);
assertEquals(6,typemap.getElementsByTagName("corba:union").getLength());
assertEquals(58,typemap.getElementsByTagName("corba:struct").getLength());
assertEquals(3,typemap.getElementsByTagName("corba:sequence").getLength());
WSDLToIDLAction idlgen=new WSDLToIDLAction();
idlgen.setBindingName("DerivedTypesCORBABinding");
idlgen.setOutputFile("nested-derivedtypes.idl");
idlgen.generateIDL(model);
File f=new File("nested-derivedtypes.idl");
assertTrue("nested-derivedtypes.idl should be generated",f.exists());
}
finally {
new File("nested-derivedtypes.idl").deleteOnExit();
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testWsAddressingAccountType() throws Exception {
try {
String fileName=getClass().getResource("/wsdl/wsaddressing_bank.wsdl").toString();
generator.setWsdlFile(fileName);
generator.addInterfaceName("Bank");
Definition model=generator.generateCORBABinding();
Document document=writer.getDocument(model);
Element typemap=getElementNode(document,"corba:typeMapping");
assertNotNull(typemap);
assertEquals(1,DOMUtils.findAllElementsByTagNameNS(typemap,"http://cxf.apache.org/bindings/corba","sequence").size());
assertEquals(2,DOMUtils.findAllElementsByTagNameNS(typemap,"http://cxf.apache.org/bindings/corba","object").size());
WSDLToIDLAction idlgen=new WSDLToIDLAction();
idlgen.setBindingName("BankCORBABinding");
idlgen.setOutputFile("wsaddressing_bank.idl");
idlgen.generateIDL(model);
File f=new File("wsaddressing_bank.idl");
assertTrue("wsaddressing_bank.idl should be generated",f.exists());
}
finally {
new File("wsaddressing_bank.idl").deleteOnExit();
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testComplexRestriction() throws Exception {
try {
URI fileName=getClass().getResource("/wsdl/complexRestriction.wsdl").toURI();
generator.setWsdlFile(new File(fileName).getAbsolutePath());
generator.addInterfaceName("TypeTestPortType");
Definition model=generator.generateCORBABinding();
Document document=writer.getDocument(model);
Element typemap=getElementNode(document,"corba:typeMapping");
assertNotNull(typemap);
assertEquals(1,typemap.getElementsByTagName("corba:struct").getLength());
}
finally {
new File("complexRestriction-corba.wsdl").deleteOnExit();
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testNestedComplexTypes() throws Exception {
try {
String fileName=getClass().getResource("/wsdl/nested_complex.wsdl").toString();
generator.setWsdlFile(fileName);
generator.addInterfaceName("X");
Definition model=generator.generateCORBABinding();
Document document=writer.getDocument(model);
Element typemap=getElementNode(document,"corba:typeMapping");
assertNotNull(typemap);
assertEquals(6,typemap.getElementsByTagName("corba:union").getLength());
assertEquals(14,typemap.getElementsByTagName("corba:struct").getLength());
assertEquals(1,typemap.getElementsByTagName("corba:enum").getLength());
assertEquals(1,typemap.getElementsByTagName("corba:array").getLength());
WSDLToIDLAction idlgen=new WSDLToIDLAction();
idlgen.setBindingName("XCORBABinding");
idlgen.setOutputFile("nested_complex.idl");
idlgen.generateIDL(model);
File f=new File("nested_complex.idl");
assertTrue("nested_complex.idl should be generated",f.exists());
}
finally {
new File("nested_complex.idl").deleteOnExit();
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testAnonymousReturnParam() throws Exception {
try {
String fileName=getClass().getResource("/wsdl/factory_pattern.wsdl").toString();
generator.setWsdlFile(fileName);
generator.addInterfaceName("Number");
Definition model=generator.generateCORBABinding();
Document document=writer.getDocument(model);
Element typemap=getElementNode(document,"corba:typeMapping");
assertNotNull(typemap);
assertEquals(3,typemap.getElementsByTagName("corba:struct").getLength());
}
finally {
new File("factory_pattern-corba.wsdl").deleteOnExit();
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testAnonType() throws Exception {
try {
String fileName=getClass().getResource("/wsdl/atype.wsdl").toString();
generator.setWsdlFile(fileName);
generator.addInterfaceName("X");
Definition model=generator.generateCORBABinding();
Document document=writer.getDocument(model);
Element typemap=getElementNode(document,"corba:typeMapping");
assertNotNull(typemap);
assertEquals(3,typemap.getElementsByTagName("corba:anonsequence").getLength());
assertEquals(2,typemap.getElementsByTagName("corba:anonarray").getLength());
assertEquals(1,typemap.getElementsByTagName("corba:array").getLength());
assertEquals(2,typemap.getElementsByTagName("corba:struct").getLength());
TypeMappingType mapType=(TypeMappingType)model.getExtensibilityElements().get(0);
Map tmap=new HashMap();
for ( CorbaType type : mapType.getStructOrExceptionOrUnion()) {
tmap.put(type.getName(),type);
}
WSDLToIDLAction idlgen=new WSDLToIDLAction();
idlgen.setBindingName("XCORBABinding");
idlgen.setOutputFile("atype.idl");
idlgen.generateIDL(model);
Array arr=(Array)tmap.get("X.A");
assertNotNull(arr);
assertEquals("ElementType is incorrect for Array Type","X._5_A",arr.getElemtype().getLocalPart());
Anonarray arr2=(Anonarray)tmap.get("X._5_A");
assertNotNull(arr2);
assertEquals("ElementType is incorrect for Anon Array Type","X._4_A",arr2.getElemtype().getLocalPart());
Anonarray arr3=(Anonarray)tmap.get("X._4_A");
assertNotNull(arr3);
assertEquals("ElementType is incorrect for Anon Array Type","X._1_A",arr3.getElemtype().getLocalPart());
Anonsequence seq=(Anonsequence)tmap.get("X._1_A");
assertNotNull(seq);
assertEquals("ElementType is incorrect for Anon Sequence Type","X._2_A",seq.getElemtype().getLocalPart());
Anonsequence seq2=(Anonsequence)tmap.get("X._2_A");
assertNotNull(seq2);
assertEquals("ElementType is incorrect for Anon Sequence Type","X._3_A",seq2.getElemtype().getLocalPart());
Anonsequence seq3=(Anonsequence)tmap.get("X._3_A");
assertNotNull(seq3);
assertEquals("ElementType is incorrect for Anon Sequence Type","long",seq3.getElemtype().getLocalPart());
File f=new File("atype.idl");
assertTrue("atype.idl should be generated",f.exists());
}
finally {
new File("atype.idl").deleteOnExit();
}
}
InternalCallVerifier EqualityVerifier
@Test public void testMultipleBindings() throws Exception {
String fileName=getClass().getResource("/wsdl/multiplePortTypes.wsdl").toString();
generator.setWsdlFile(fileName);
generator.setAllBindings(true);
Definition model=generator.generateCORBABinding();
assertEquals("All bindings should be generated.",2,model.getAllBindings().size());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testImportSchemaInTypes() throws Exception {
try {
URI fileName=getClass().getResource("/wsdl/importType.wsdl").toURI();
generator.setWsdlFile(new File(fileName).getAbsolutePath());
generator.addInterfaceName("TypeTestPortType");
Definition model=generator.generateCORBABinding();
Document document=writer.getDocument(model);
Element typemap=getElementNode(document,"corba:typeMapping");
assertNotNull(typemap);
assertEquals(1,typemap.getElementsByTagName("corba:enum").getLength());
assertEquals(1,typemap.getElementsByTagName("corba:sequence").getLength());
}
finally {
new File("importType-corba.wsdl").deleteOnExit();
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testNestedType() throws Exception {
try {
String fileName=getClass().getResource("/wsdl/nested.wsdl").toString();
generator.setWsdlFile(fileName);
generator.addInterfaceName("TypeInheritancePortType");
Definition model=generator.generateCORBABinding();
Document document=writer.getDocument(model);
Element typemap=getElementNode(document,"corba:typeMapping");
assertNotNull(typemap);
assertEquals(4,typemap.getElementsByTagName("corba:union").getLength());
assertEquals(23,typemap.getElementsByTagName("corba:struct").getLength());
assertEquals(1,typemap.getElementsByTagName("corba:anonstring").getLength());
WSDLToIDLAction idlgen=new WSDLToIDLAction();
idlgen.setBindingName("TypeInheritanceCORBABinding");
idlgen.setOutputFile("nested.idl");
idlgen.generateIDL(model);
File f=new File("nested.idl");
assertTrue("nested.idl should be generated",f.exists());
}
finally {
new File("nested.idl").deleteOnExit();
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testListType() throws Exception {
try {
URI fileName=getClass().getResource("/wsdl/listType.wsdl").toURI();
generator.setWsdlFile(new File(fileName).getAbsolutePath());
generator.addInterfaceName("TypeTestPortType");
Definition model=generator.generateCORBABinding();
Document document=writer.getDocument(model);
Element typemap=getElementNode(document,"corba:typeMapping");
assertNotNull(typemap);
assertEquals(1,typemap.getElementsByTagName("corba:enum").getLength());
assertEquals(1,typemap.getElementsByTagName("corba:sequence").getLength());
}
finally {
new File("listType-corba.wsdl").deleteOnExit();
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCorbaExceptionComplextype() throws Exception {
try {
String fileName=getClass().getResource("/wsdl/databaseService.wsdl").toString();
generator.setWsdlFile(fileName);
generator.addInterfaceName("Database");
Definition model=generator.generateCORBABinding();
Document document=writer.getDocument(model);
Element typemap=getElementNode(document,"corba:typeMapping");
assertNotNull(typemap);
assertEquals(2,typemap.getElementsByTagName("corba:struct").getLength());
assertEquals(1,typemap.getElementsByTagName("corba:exception").getLength());
assertEquals(1,typemap.getElementsByTagName("corba:anonsequence").getLength());
}
finally {
new File("databaseService-corba.wsdl").deleteOnExit();
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testWsAddressingBankType() throws Exception {
try {
String fileName=getClass().getResource("/wsdl/wsaddressing_account.wsdl").toString();
generator.setWsdlFile(fileName);
generator.addInterfaceName("Account");
Definition model=generator.generateCORBABinding();
Document document=writer.getDocument(model);
Element typemap=getElementNode(document,"corba:typeMapping");
assertNotNull(typemap);
assertEquals(1,typemap.getElementsByTagName("corba:object").getLength());
WSDLToIDLAction idlgen=new WSDLToIDLAction();
idlgen.setBindingName("AccountCORBABinding");
idlgen.setOutputFile("wsaddressing_account.idl");
idlgen.generateIDL(model);
File f=new File("wsaddressing_account.idl");
assertTrue("wsaddressing_account.idl should be generated",f.exists());
}
finally {
new File("wsaddressing_account.idl").deleteOnExit();
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testComplextypeDerivedSimpletype() throws Exception {
try {
String fileName=getClass().getResource("/wsdl/complex_types.wsdl").toString();
generator.setWsdlFile(fileName);
generator.addInterfaceName("TypeTestPortType");
Definition model=generator.generateCORBABinding();
Document document=writer.getDocument(model);
Element typemap=getElementNode(document,"corba:typeMapping");
assertNotNull(typemap);
assertEquals(8,typemap.getElementsByTagName("corba:struct").getLength());
assertEquals(1,typemap.getElementsByTagName("corba:fixed").getLength());
assertEquals(1,typemap.getElementsByTagName("corba:array").getLength());
assertEquals(5,typemap.getElementsByTagName("corba:union").getLength());
assertEquals(3,typemap.getElementsByTagName("corba:sequence").getLength());
}
finally {
new File("complex_types-corba.wsdl").deleteOnExit();
}
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testRestrictedStruct() throws Exception {
try {
URI fileName=getClass().getResource("/wsdl/restrictedStruct.wsdl").toURI();
generator.setWsdlFile(new File(fileName).getAbsolutePath());
generator.addInterfaceName("TypeTestPortType");
Definition model=generator.generateCORBABinding();
Document document=writer.getDocument(model);
Element typemap=getElementNode(document,"corba:typeMapping");
assertNotNull(typemap);
assertEquals(7,typemap.getElementsByTagName("corba:struct").getLength());
assertEquals(3,typemap.getElementsByTagName("corba:union").getLength());
}
finally {
new File("restrictedStruct-corba.wsdl").deleteOnExit();
}
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testAnyType() throws Exception {
try {
String fileName=getClass().getResource("/wsdl/any.wsdl").toString();
generator.setWsdlFile(fileName);
generator.addInterfaceName("anyInterface");
Definition model=generator.generateCORBABinding();
TypeMappingType mapType=(TypeMappingType)model.getExtensibilityElements().get(0);
assertEquals(5,mapType.getStructOrExceptionOrUnion().size());
int strcnt=0;
int unioncnt=0;
for ( CorbaType corbaType : mapType.getStructOrExceptionOrUnion()) {
if (corbaType instanceof Struct) {
strcnt++;
}
if (corbaType instanceof Union) {
unioncnt++;
}
}
assertNotNull(mapType);
assertEquals(3,strcnt);
assertEquals(2,unioncnt);
WSDLToIDLAction idlgen=new WSDLToIDLAction();
idlgen.setBindingName("anyInterfaceCORBABinding");
idlgen.setOutputFile("any.idl");
idlgen.generateIDL(model);
File f=new File("any.idl");
assertTrue("any.idl should be generated",f.exists());
}
finally {
new File("any.idl").deleteOnExit();
}
}
InternalCallVerifier EqualityVerifier
@Test public void testSetCorbaAddressFile() throws Exception {
try {
URI fileName=getClass().getResource("/wsdl/datetime.wsdl").toURI();
generator.setWsdlFile(new File(fileName).getAbsolutePath());
generator.addInterfaceName("BasePortType");
Definition model=generator.generateCORBABinding();
QName name=new QName("http://schemas.apache.org/idl/datetime.idl","BaseCORBAService","tns");
Service service=model.getService(name);
Port port=service.getPort("BaseCORBAPort");
AddressType addressType=(AddressType)port.getExtensibilityElements().get(0);
String address=addressType.getLocation();
assertEquals("file:./Base.ref",address);
URL idl=getClass().getResource("/wsdl/addressfile.txt");
String filename=new File(idl.toURI()).getAbsolutePath();
generator.setAddressFile(filename);
model=generator.generateCORBABinding();
service=model.getService(name);
port=service.getPort("BaseCORBAPort");
addressType=(AddressType)port.getExtensibilityElements().get(0);
address=addressType.getLocation();
assertEquals("corbaloc::localhost:60000/hw",address);
}
finally {
new File("datetime-corba.wsdl").deleteOnExit();
}
}
InternalCallVerifier EqualityVerifier
@Test public void testSetCorbaAddress() throws Exception {
try {
String fileName=getClass().getResource("/wsdl/datetime.wsdl").toString();
generator.setWsdlFile(fileName);
generator.addInterfaceName("BasePortType");
Definition model=generator.generateCORBABinding();
QName name=new QName("http://schemas.apache.org/idl/datetime.idl","BaseCORBAService","tns");
Service service=model.getService(name);
Port port=service.getPort("BaseCORBAPort");
AddressType addressType=(AddressType)port.getExtensibilityElements().get(0);
String address=addressType.getLocation();
assertEquals("file:./Base.ref",address);
generator.setAddress("corbaloc::localhost:40000/hw");
model=generator.generateCORBABinding();
service=model.getService(name);
port=service.getPort("BaseCORBAPort");
addressType=(AddressType)port.getExtensibilityElements().get(0);
address=addressType.getLocation();
assertEquals("corbaloc::localhost:40000/hw",address);
}
finally {
new File("datetime-corba.wsdl").deleteOnExit();
}
}
APIUtilityVerifier IterativeVerifier BranchVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testTypeInheritance() throws Exception {
try {
String fileName=getClass().getResource("/wsdl/TypeInheritance.wsdl").toString();
generator.setWsdlFile(fileName);
generator.addInterfaceName("TypeInheritancePortType");
Definition model=generator.generateCORBABinding();
Document document=writer.getDocument(model);
Element typemap=getElementNode(document,"corba:typeMapping");
assertNotNull(typemap);
assertEquals(3,typemap.getElementsByTagName("corba:union").getLength());
assertEquals(1,typemap.getElementsByTagName("corba:anonstring").getLength());
assertEquals(17,typemap.getElementsByTagName("corba:struct").getLength());
TypeMappingType mapType=(TypeMappingType)model.getExtensibilityElements().get(0);
WSDLToIDLAction idlgen=new WSDLToIDLAction();
idlgen.setBindingName("TypeInheritanceCORBABinding");
idlgen.setOutputFile("typeInherit.idl");
idlgen.generateIDL(model);
List types=mapType.getStructOrExceptionOrUnion();
for (int i=0; i < types.size(); i++) {
CorbaType type=types.get(i);
if ("Type5SequenceStruct".equals(type.getName())) {
assertTrue("Name is incorrect for Type5SequenceStruct Type",type instanceof Struct);
assertEquals("Type is incorrect for AnonSequence Type","Type5",type.getType().getLocalPart());
}
else if ("attrib2Type".equals(type.getName())) {
assertTrue("Name is incorrect for attrib2Type Type",type instanceof Anonstring);
assertEquals("Type is incorrect for AnonString Type","string",type.getType().getLocalPart());
}
else if ("attrib2Type_nil".equals(type.getName())) {
assertTrue("Name is incorrect for Struct Type",type instanceof Union);
assertEquals("Type is incorrect for AnonSequence Type","attrib2",type.getType().getLocalPart());
}
}
File f=new File("typeInherit.idl");
assertTrue("typeInherit.idl should be generated",f.exists());
}
finally {
new File("typeInherit.idl").deleteOnExit();
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testNestedInterfaceTypes() throws Exception {
try {
String fileName=getClass().getResource("/wsdl/nested_interfaces.wsdl").toString();
generator.setWsdlFile(fileName);
generator.addInterfaceName("C.C1");
Definition model=generator.generateCORBABinding();
Document document=writer.getDocument(model);
Element typemap=getElementNode(document,"corba:typeMapping");
assertNotNull(typemap);
assertEquals(1,typemap.getElementsByTagName("corba:anonstring").getLength());
assertEquals(9,typemap.getElementsByTagName("corba:struct").getLength());
WSDLToIDLAction idlgen=new WSDLToIDLAction();
idlgen.setBindingName("C.C1CORBABinding");
idlgen.setOutputFile("nested_interfaces.idl");
idlgen.generateIDL(model);
File f=new File("nested_interfaces.idl");
assertTrue("nested_interfaces.idl should be generated",f.exists());
}
finally {
new File("nested_interfaces.idl").deleteOnExit();
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testDateTimeTypes() throws Exception {
try {
String fileName=getClass().getResource("/wsdl/datetime.wsdl").toString();
generator.setWsdlFile(fileName);
generator.addInterfaceName("BasePortType");
Definition model=generator.generateCORBABinding();
Document document=writer.getDocument(model);
Element typemap=getElementNode(document,"corba:typeMapping");
assertNotNull(typemap);
assertEquals(2,typemap.getElementsByTagName("corba:union").getLength());
assertEquals(2,typemap.getElementsByTagName("corba:struct").getLength());
WSDLToIDLAction idlgen=new WSDLToIDLAction();
idlgen.setBindingName("BaseCORBABinding");
idlgen.setOutputFile("datetime.idl");
idlgen.generateIDL(model);
File f=new File("datetime.idl");
assertTrue("datetime.idl should be generated",f.exists());
}
finally {
new File("datetime.idl").deleteOnExit();
}
}
APIUtilityVerifier IterativeVerifier BranchVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testAnonFixedType() throws Exception {
try {
String fileName=getClass().getResource("/wsdl/anonfixed.wsdl").toString();
generator.setWsdlFile(fileName);
generator.addInterfaceName("X");
Definition model=generator.generateCORBABinding();
Document document=writer.getDocument(model);
Element typemap=getElementNode(document,"corba:typeMapping");
assertNotNull(typemap);
assertEquals(1,typemap.getElementsByTagName("corba:anonfixed").getLength());
assertEquals(1,typemap.getElementsByTagName("corba:anonstring").getLength());
assertEquals(3,typemap.getElementsByTagName("corba:struct").getLength());
TypeMappingType mapType=(TypeMappingType)model.getExtensibilityElements().get(0);
WSDLToIDLAction idlgen=new WSDLToIDLAction();
idlgen.setBindingName("XCORBABinding");
idlgen.setOutputFile("atype.idl");
idlgen.generateIDL(model);
List types=mapType.getStructOrExceptionOrUnion();
for (int i=0; i < types.size(); i++) {
CorbaType type=types.get(i);
if (type instanceof Anonstring) {
Anonstring str=(Anonstring)type;
assertEquals("Name is incorrect for Array Type","X._1_S",str.getName());
assertEquals("Type is incorrect for AnonString Type","string",str.getType().getLocalPart());
}
else if (type instanceof Anonfixed) {
Anonfixed fx=(Anonfixed)type;
assertEquals("Name is incorrect for Anon Array Type","X._2_S",fx.getName());
assertEquals("Type is incorrect for AnonFixed Type","decimal",fx.getType().getLocalPart());
}
else if (type instanceof Struct) {
Struct struct=(Struct)type;
String[] testResult;
if ("X.op_a".equals(struct.getName())) {
testResult=new String[]{"X.op_a","X.op_a","p1","X.S","p2","X.S"};
}
else if ("X.op_aResult".equals(struct.getName())) {
testResult=new String[]{"X.op_aResult","X.op_aResult","return","X.S","p2","X.S"};
}
else {
testResult=new String[]{"X.S","X.S","str","X._1_S","fx","X._2_S"};
}
assertEquals("Name is incorrect for Anon Array Type",testResult[0],struct.getName());
assertEquals("Type is incorrect for Struct Type",testResult[1],struct.getType().getLocalPart());
assertEquals("Name for first Struct Member Type is incorrect",testResult[2],struct.getMember().get(0).getName());
assertEquals("Idltype for first Struct Member Type is incorrect",testResult[3],struct.getMember().get(0).getIdltype().getLocalPart());
assertEquals("Name for second Struct Member Type is incorrect",testResult[4],struct.getMember().get(1).getName());
assertEquals("Idltype for second Struct Member Type is incorrect",testResult[5],struct.getMember().get(1).getIdltype().getLocalPart());
}
else {
}
}
File f=new File("atype.idl");
assertTrue("atype.idl should be generated",f.exists());
}
finally {
new File("atype.idl").deleteOnExit();
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testWsAddressingTypes() throws Exception {
try {
String fileName=getClass().getResource("/wsdl/wsaddressing_server.wsdl").toString();
generator.setWsdlFile(fileName);
generator.addInterfaceName("TestServer");
Definition model=generator.generateCORBABinding();
Document document=writer.getDocument(model);
Element typemap=getElementNode(document,"corba:typeMapping");
assertNotNull(typemap);
assertEquals(1,typemap.getElementsByTagName("corba:object").getLength());
WSDLToIDLAction idlgen=new WSDLToIDLAction();
idlgen.setBindingName("TestServerCORBABinding");
idlgen.setOutputFile("wsaddressing_server.idl");
idlgen.generateIDL(model);
File f=new File("wsaddressing_server.idl");
assertTrue("wsaddressing_server.idl should be generated",f.exists());
}
finally {
new File("wsaddressing_server.idl").deleteOnExit();
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testNillableType() throws Exception {
try {
String fileName=getClass().getResource("/wsdl/nillable.wsdl").toString();
generator.setWsdlFile(fileName);
generator.addInterfaceName("NillablePortType");
Definition model=generator.generateCORBABinding();
Document document=writer.getDocument(model);
Element typemap=getElementNode(document,"corba:typeMapping");
assertNotNull(typemap);
assertEquals(2,typemap.getElementsByTagName("corba:union").getLength());
assertEquals(1,typemap.getElementsByTagName("corba:struct").getLength());
TypeMappingType mapType=(TypeMappingType)model.getExtensibilityElements().get(0);
WSDLToIDLAction idlgen=new WSDLToIDLAction();
idlgen.setBindingName("NillableCORBABinding");
idlgen.setOutputFile("nillable.idl");
idlgen.generateIDL(model);
Union un=(Union)mapType.getStructOrExceptionOrUnion().get(2);
assertEquals("Name is incorrect for Union Type","long_nil",un.getName());
assertEquals("Type is incorrect for Union Type","PEl",un.getType().getLocalPart());
Unionbranch unbranch=un.getUnionbranch().get(0);
assertEquals("Name is incorrect for UnionBranch Type","value",unbranch.getName());
assertEquals("Type is incorrect for UnionBranch Type","long",unbranch.getIdltype().getLocalPart());
File f=new File("nillable.idl");
assertTrue("nillable.idl should be generated",f.exists());
}
finally {
new File("nillable.idl").deleteOnExit();
}
}
Class: org.apache.cxf.tools.java2ws.AegisTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testAegisReconfigureDatabinding() throws Exception {
final String sei=org.apache.cxf.tools.fortest.aegis2ws.TestAegisSEI.class.getName();
String[] args=new String[]{"-wsdl","-o",output.getPath() + "/aegis.wsdl","-beans",new File(inputData,"revisedAegisDefaultBeans.xml").getAbsolutePath(),"-verbose","-s",output.getPath(),"-frontend","jaxws","-databinding","aegis","-client","-server",sei};
File wsdlFile=null;
wsdlFile=outputFile("aegis.wsdl");
JavaToWS.main(args);
assertTrue("wsdl is not generated " + getStdErr(),wsdlFile.exists());
WSDLReader reader=WSDLFactory.newInstance().newWSDLReader();
reader.setFeature("javax.wsdl.verbose",false);
Definition def=reader.readWSDL(wsdlFile.toURI().toURL().toString());
Document wsdl=WSDLFactory.newInstance().newWSDLWriter().getDocument(def);
assertValid("//xsd:element[@type='ns0:Something']",wsdl);
XPathUtils xpu=new XPathUtils(getNSMap());
String s=(String)xpu.getValue("//xsd:complexType[@name='takeSomething']/" + "xsd:sequence/xsd:element[@name='arg0']/@minOccurs",wsdl,XPathConstants.STRING);
assertEquals("50",s);
assertFalse(xpu.isExist("//xsd:complexType[@name='Something']/xsd:sequence/" + "xsd:element[@name='singular']/@minOccurs",wsdl,XPathConstants.NODE));
}
Class: org.apache.cxf.tools.java2ws.JavaToWSTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testXmlJavaTypeAdapter() throws Exception {
String[] args=new String[]{"-o",output.getPath() + "/xmladapter.wsdl","-verbose","-wsdl","org.apache.xmladapter.GreeterImpl"};
JavaToWS.main(args);
File file=new File(output.getPath() + "/xmladapter.wsdl");
Document doc=StaxUtils.read(file);
Map map=new HashMap();
map.put("xsd","http://www.w3.org/2001/XMLSchema");
map.put("wsdl","http://schemas.xmlsoap.org/wsdl/");
map.put("soap","http://schemas.xmlsoap.org/wsdl/soap/");
XPathUtils util=new XPathUtils(map);
Element node=(Element)util.getValueNode("//xsd:element[@name='arg0']",doc);
assertNotNull(node);
assertEquals("0",node.getAttribute("minOccurs"));
assertTrue(node.getAttribute("type").contains("string"));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testXmlList() throws Exception {
String[] args=new String[]{"-o",output.getPath() + "/xml-list.wsdl","-verbose","-wsdl","org.apache.cxf.tools.fortest.xmllist.AddNumbersPortType"};
JavaToWS.main(args);
File file=new File(output.getPath() + "/xml-list.wsdl");
Document doc=StaxUtils.read(file);
Map map=new HashMap();
map.put("xsd","http://www.w3.org/2001/XMLSchema");
map.put("wsdl","http://schemas.xmlsoap.org/wsdl/");
map.put("soap","http://schemas.xmlsoap.org/wsdl/soap/");
XPathUtils util=new XPathUtils(map);
Element node=(Element)util.getValueNode("//xsd:list",doc);
assertNotNull(node);
assertTrue(node.getAttribute("itemType").contains("string"));
}
Class: org.apache.cxf.tools.java2wsdl.generator.WSDLGeneratorFactoryTest BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testNewWSDL11Generator(){
WSDLGeneratorFactory factory=new WSDLGeneratorFactory();
factory.setWSDLVersion(WSDLConstants.WSDLVersion.WSDL11);
AbstractGenerator> generator=factory.newGenerator();
assertNotNull(generator);
assertTrue(generator instanceof WSDL11Generator);
}
Class: org.apache.cxf.tools.java2wsdl.generator.wsdl11.DateTypeCustomGeneratorTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void getGetDateType(){
assertNull(gen.getDateType());
gen.setServiceModel(getServiceInfo(org.apache.cxf.tools.fortest.jaxws.rpc.GreeterFault.class));
assertNull(gen.getDateType());
gen.setServiceModel(getServiceInfo(EchoDate.class));
assertEquals(Date.class,gen.getDateType());
gen.setServiceModel(getServiceInfo(EchoCalendar.class));
assertEquals(Calendar.class,gen.getDateType());
}
InternalCallVerifier EqualityVerifier
@Test public void testGenerateExternalStyle() throws Exception {
gen.setAllowImports(true);
gen.addSchemaFiles(Arrays.asList(new String[]{"hello_schema1.xsd","hello_schema2.xsd"}));
gen.setWSDLName("date_external");
gen.setServiceModel(getServiceInfo(EchoDate.class));
assertEquals(Date.class,gen.getDateType());
URI expectedFile=getClass().getResource("expected/date.xjb").toURI();
assertFileEquals(new File(expectedFile),gen.generate(output));
gen.setWSDLName("calendar_external");
gen.setServiceModel(getServiceInfo(EchoCalendar.class));
assertEquals(Calendar.class,gen.getDateType());
expectedFile=getClass().getResource("expected/calendar.xjb").toURI();
assertFileEquals(new File(expectedFile),gen.generate(output));
}
InternalCallVerifier EqualityVerifier
@Test public void testGenerateEmbedStyle() throws Exception {
gen.setWSDLName("date_embed");
gen.setServiceModel(getServiceInfo(EchoDate.class));
assertEquals(Date.class,gen.getDateType());
URI expectedFile=getClass().getResource("expected/date_embed.xml").toURI();
assertFileEquals(new File(expectedFile),gen.generate(output));
gen.setWSDLName("calendar_embed");
gen.setServiceModel(getServiceInfo(EchoCalendar.class));
assertEquals(Calendar.class,gen.getDateType());
expectedFile=getClass().getResource("expected/calendar_embed.xml").toURI();
assertFileEquals(new File(expectedFile),gen.generate(output));
}
BooleanVerifier InternalCallVerifier
@Test public void testGetJAXBCustFile(){
gen.setWSDLName("demo");
assertTrue(gen.getJAXBCustFile(new File(".")).toString().endsWith("demo.xjb"));
}
Class: org.apache.cxf.tools.java2wsdl.generator.wsdl11.annotator.WrapperBeanAnnotatorTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testAnnotate(){
String pkgName="org.apache.cxf.tools.fortest.withannotation.doc.jaxws";
WrapperBeanClass clz=new WrapperBeanClass();
clz.setFullClassName(pkgName + ".SayHi");
clz.setElementName(new QName("http://doc.withannotation.fortest.tools.cxf.apache.org/","sayHi"));
clz.annotate(new WrapperBeanAnnotator());
List annotations=clz.getAnnotations();
String expectedNamespace="http://doc.withannotation.fortest.tools.cxf.apache.org/";
JAnnotation rootElementAnnotation=annotations.get(0);
assertEquals("@XmlRootElement(name = \"sayHi\", " + "namespace = \"" + expectedNamespace + "\")",rootElementAnnotation.toString());
JAnnotation xmlTypeAnnotation=annotations.get(2);
assertEquals("@XmlType(name = \"sayHi\", " + "namespace = \"" + expectedNamespace + "\")",xmlTypeAnnotation.toString());
JAnnotation accessorTypeAnnotation=annotations.get(1);
assertEquals("@XmlAccessorType(XmlAccessType.FIELD)",accessorTypeAnnotation.toString());
WrapperBeanClass resWrapperClass=new WrapperBeanClass();
resWrapperClass.setFullClassName(pkgName + ".SayHiResponse");
resWrapperClass.setElementName(new QName(expectedNamespace,"sayHiResponse"));
resWrapperClass.annotate(new WrapperBeanAnnotator());
annotations=resWrapperClass.getAnnotations();
rootElementAnnotation=annotations.get(0);
assertEquals("@XmlRootElement(name = \"sayHiResponse\", " + "namespace = \"" + expectedNamespace + "\")",rootElementAnnotation.toString());
accessorTypeAnnotation=annotations.get(1);
assertEquals("@XmlAccessorType(XmlAccessType.FIELD)",accessorTypeAnnotation.toString());
xmlTypeAnnotation=annotations.get(2);
assertEquals("@XmlType(name = \"sayHiResponse\", " + "namespace = \"" + expectedNamespace + "\")",xmlTypeAnnotation.toString());
}
Class: org.apache.cxf.tools.java2wsdl.generator.wsdl11.annotator.WrapperBeanFieldAnnotatorTest InternalCallVerifier EqualityVerifier
@Test public void testAnnotate(){
JavaClass clz=new JavaClass();
clz.setFullClassName("org.apache.cxf.tools.fortest.withannotation.doc.jaxws.SayHi");
JavaField reqField=new JavaField("array","String[]","http://doc.withannotation.fortest.tools.cxf.apache.org/");
reqField.setOwner(clz);
List annotation=reqField.getAnnotations();
assertEquals(0,annotation.size());
reqField.annotate(new WrapperBeanFieldAnnotator());
annotation=reqField.getAnnotations();
String expectedNamespace="http://doc.withannotation.fortest.tools.cxf.apache.org/";
assertEquals("@XmlElement(name = \"array\", namespace = \"" + expectedNamespace + "\")",annotation.get(0).toString());
clz.setFullClassName("org.apache.cxf.tools.fortest.withannotation.doc.jaxws.SayHiResponse");
JavaField resField=new JavaField("return","String[]","http://doc.withannotation.fortest.tools.cxf.apache.org/");
resField.setOwner(clz);
resField.annotate(new WrapperBeanFieldAnnotator());
annotation=resField.getAnnotations();
assertEquals("@XmlElement(name = \"return\", namespace = \"" + expectedNamespace + "\")",annotation.get(0).toString());
}
Class: org.apache.cxf.tools.java2wsdl.processor.FrontendFactoryTest InternalCallVerifier EqualityVerifier
@Test public void testJaxwsStyle(){
factory.setServiceClass(Stock.class);
assertEquals(FrontendFactory.Style.Jaxws,factory.discoverStyle());
}
InternalCallVerifier EqualityVerifier
@Test public void testDefaultStyle(){
factory.setServiceClass(null);
assertEquals(FrontendFactory.Style.Jaxws,factory.discoverStyle());
}
InternalCallVerifier EqualityVerifier
@Test public void testSimpleStyle(){
factory.setServiceClass(Hello.class);
assertEquals(FrontendFactory.Style.Simple,factory.discoverStyle());
}
Class: org.apache.cxf.tools.java2wsdl.processor.JavaToProcessorTest BooleanVerifier InternalCallVerifier
@Test public void testIsSOAP12() throws Exception {
env.put(ToolConstants.CFG_CLASSNAME,"org.apache.cxf.tools.fortest.withannotation.doc.Stock12Impl");
processor.setEnvironment(env);
assertTrue(processor.isSOAP12());
env.put(ToolConstants.CFG_CLASSNAME,"org.apache.hello_world_soap12_http.Greeter");
assertFalse(processor.isSOAP12());
env.put(ToolConstants.CFG_SOAP12,"soap12");
assertTrue(processor.isSOAP12());
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testSimpleClass() throws Exception {
env.put(ToolConstants.CFG_OUTPUTFILE,output.getPath() + "/doc_wrapped_bare.wsdl");
env.put(ToolConstants.CFG_CLASSNAME,"org.apache.cxf.tools.fortest.simple.Hello");
processor.setEnvironment(env);
processor.process();
File wsdlFile=new File(output,"doc_wrapped_bare.wsdl");
assertTrue("Fail to generate wsdl file: " + wsdlFile.toString(),wsdlFile.exists());
String tns="http://simple.fortest.tools.cxf.apache.org/";
Definition def=wsdlHelper.getDefinition(wsdlFile);
assertNotNull(def);
Service wsdlService=def.getService(new QName(tns,"Hello"));
assertNotNull("Generate WSDL Service Error",wsdlService);
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testDocLitUseClassPathFlag() throws Exception {
File classFile=new java.io.File(output.getCanonicalPath() + "/classes");
classFile.mkdir();
System.setProperty("java.class.path",getClassPath() + classFile.getCanonicalPath() + File.separatorChar);
env.put(ToolConstants.CFG_COMPILE,ToolConstants.CFG_COMPILE);
env.put(ToolConstants.CFG_CLASSDIR,output.getCanonicalPath() + "/classes");
env.put(FrontEndProfile.class,PluginLoader.getInstance().getFrontEndProfile("jaxws"));
env.put(DataBindingProfile.class,PluginLoader.getInstance().getDataBindingProfile("jaxb"));
env.put(ToolConstants.CFG_OUTPUTDIR,output.getCanonicalPath());
env.put(ToolConstants.CFG_PACKAGENAME,"org.apache.cxf.classpath");
env.put(ToolConstants.CFG_CLASSDIR,output.getCanonicalPath() + "/classes");
env.put(ToolConstants.CFG_WSDLURL,getLocation("/wsdl/hello_world_doc_lit.wsdl"));
JAXWSContainer w2jProcessor=new JAXWSContainer(null);
w2jProcessor.setContext(env);
w2jProcessor.execute();
String tns="http://apache.org/sepecifiedTns";
String serviceName="cxfService";
String portName="cxfPort";
System.setProperty("java.class.path","");
String[] args=new String[]{"-o","java2wsdl.wsdl","-cp",classFile.getCanonicalPath(),"-t",tns,"-servicename",serviceName,"-portname",portName,"-soap12","-d",output.getPath(),"-wsdl","org.apache.cxf.classpath.Greeter"};
JavaToWS.main(args);
File wsdlFile=new File(output,"java2wsdl.wsdl");
assertTrue("Generate Wsdl Fail",wsdlFile.exists());
Definition def=wsdlHelper.getDefinition(wsdlFile);
Service wsdlService=def.getService(new QName(tns,serviceName));
assertNotNull("Generate WSDL Service Error",wsdlService);
Port wsdlPort=wsdlService.getPort(portName);
assertNotNull("Generate service port error ",wsdlPort);
}
InternalCallVerifier EqualityVerifier
@Test public void testGetWSDLVersion(){
processor.setEnvironment(new ToolContext());
assertEquals(WSDLConstants.WSDLVersion.WSDL11,processor.getWSDLVersion());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testExceptionTypeAdapter() throws Exception {
env.put(ToolConstants.CFG_OUTPUTFILE,output.getPath() + "/exception-type-adapter.wsdl");
env.put(ToolConstants.CFG_CLASSNAME,"org.apache.cxf.tools.fortest.exception.TypeAdapterEcho");
env.put(ToolConstants.CFG_VERBOSE,ToolConstants.CFG_VERBOSE);
try {
processor.setEnvironment(env);
processor.process();
}
catch ( Exception e) {
e.printStackTrace();
}
File wsdlFile=new File(output,"exception-type-adapter.wsdl");
assertTrue(wsdlFile.exists());
Document doc=StaxUtils.read(wsdlFile);
Map map=new HashMap();
map.put("xsd","http://www.w3.org/2001/XMLSchema");
XPathUtils util=new XPathUtils(map);
Node nd=util.getValueNode("//xsd:complexType[@name='myClass2']",doc);
assertNotNull(nd);
nd=util.getValueNode("//xsd:element[@name='adapted']",doc);
assertNotNull(nd);
String at=((Element)nd).getAttribute("type");
assertTrue(at.contains("myClass2"));
assertEquals("0",((Element)nd).getAttribute("minOccurs"));
}
APIUtilityVerifier IterativeVerifier BranchVerifier UtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testPropOrderInException2() throws Exception {
env.put(ToolConstants.CFG_OUTPUTFILE,output.getPath() + "/exception_prop_order2.wsdl");
env.put(ToolConstants.CFG_CLASSNAME,"org.apache.cxf.tools.fortest.exception.Echo5Impl");
env.put(ToolConstants.CFG_VERBOSE,ToolConstants.CFG_VERBOSE);
try {
processor.setEnvironment(env);
processor.process();
}
catch ( Exception e) {
e.printStackTrace();
}
File wsdlFile=new File(output,"exception_prop_order2.wsdl");
assertTrue(wsdlFile.exists());
Document doc=StaxUtils.read(wsdlFile);
Map map=new HashMap();
map.put("xsd","http://www.w3.org/2001/XMLSchema");
map.put("wsdl","http://schemas.xmlsoap.org/wsdl/");
map.put("soap","http://schemas.xmlsoap.org/wsdl/soap/");
XPathUtils util=new XPathUtils(map);
Element summary=(Element)util.getValueNode("//xsd:element[@name='summary']",doc);
Element from=(Element)util.getValueNode("//xsd:element[@name='from']",doc);
Element id=(Element)util.getValueNode("//xsd:element[@name='id']",doc);
assertNotNull(summary);
assertNotNull(from);
assertNotNull(id);
Node nd=summary.getNextSibling();
while (nd != null) {
if (nd == from) {
from=null;
}
else if (nd == id) {
if (from != null) {
fail("id before from");
}
id=null;
}
nd=nd.getNextSibling();
}
assertNull(id);
assertNull(from);
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testGetOutputDir() throws Exception {
processor.setEnvironment(env);
File wsdlLocation=new File("http:\\\\example.com?wsdl");
File f=processor.getOutputDir(wsdlLocation);
assertNotNull(f);
assertTrue(f.exists());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testExceptionRefNillable() throws Exception {
env.put(ToolConstants.CFG_OUTPUTFILE,output.getPath() + "/exception-ref-nillable.wsdl");
env.put(ToolConstants.CFG_CLASSNAME,"org.apache.cxf.tools.fortest.exception.Echo3Impl");
env.put(ToolConstants.CFG_VERBOSE,ToolConstants.CFG_VERBOSE);
try {
processor.setEnvironment(env);
processor.process();
}
catch ( Exception e) {
e.printStackTrace();
}
File wsdlFile=new File(output,"exception-ref-nillable.wsdl");
assertTrue(wsdlFile.exists());
Document doc=StaxUtils.read(wsdlFile);
Map map=new HashMap();
map.put("xsd","http://www.w3.org/2001/XMLSchema");
map.put("wsdl","http://schemas.xmlsoap.org/wsdl/");
map.put("soap","http://schemas.xmlsoap.org/wsdl/soap/");
map.put("tns","http://cxf.apache.org/test/HelloService");
XPathUtils util=new XPathUtils(map);
Element el=(Element)util.getValueNode("//xsd:element[@ref]",doc);
assertNotNull(el);
assertTrue(el.getAttribute("ref").contains("item"));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testTransientMessage() throws Exception {
env.put(ToolConstants.CFG_OUTPUTFILE,output.getPath() + "/transient_message.wsdl");
env.put(ToolConstants.CFG_CLASSNAME,"org.apache.cxf.tools.fortest.exception.Echo4");
env.put(ToolConstants.CFG_VERBOSE,ToolConstants.CFG_VERBOSE);
try {
processor.setEnvironment(env);
processor.process();
}
catch ( Exception e) {
e.printStackTrace();
}
File wsdlFile=new File(output,"transient_message.wsdl");
assertTrue(wsdlFile.exists());
Document doc=StaxUtils.read(wsdlFile);
Map map=new HashMap();
map.put("xsd","http://www.w3.org/2001/XMLSchema");
map.put("wsdl","http://schemas.xmlsoap.org/wsdl/");
map.put("soap","http://schemas.xmlsoap.org/wsdl/soap/");
map.put("tns","http://cxf.apache.org/test/HelloService");
XPathUtils util=new XPathUtils(map);
String path="//xsd:complexType[@name='TransientMessageException']//xsd:sequence/xsd:element[@name='message']";
Element nd=(Element)util.getValueNode(path,doc);
assertNull(nd);
List sl=CastUtils.cast((List>)env.get("serviceList"));
FaultInfo mi=sl.get(0).getInterface().getOperation(new QName("http://cxf.apache.org/test/HelloService","echo")).getFault(new QName("http://cxf.apache.org/test/HelloService","TransientMessageException"));
MessagePartInfo mpi=mi.getMessagePart(0);
JAXBContext ctx=JAXBContext.newInstance(String.class,Integer.TYPE);
StringWriter sw=new StringWriter();
XMLStreamWriter writer=StaxUtils.createXMLStreamWriter(sw);
TransientMessageException tme=new TransientMessageException(12,"Exception Message");
Marshaller ms=ctx.createMarshaller();
ms.setProperty(Marshaller.JAXB_FRAGMENT,true);
JAXBEncoderDecoder.marshallException(ms,tme,mpi,writer);
writer.flush();
writer.close();
assertEquals(-1,sw.getBuffer().indexOf("Exception Message"));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testException() throws Exception {
env.put(ToolConstants.CFG_OUTPUTFILE,output.getPath() + "/exception.wsdl");
env.put(ToolConstants.CFG_CLASSNAME,"org.apache.cxf.tools.fortest.simple.Caculator");
env.put(ToolConstants.CFG_VERBOSE,ToolConstants.CFG_VERBOSE);
try {
processor.setEnvironment(env);
processor.process();
}
catch ( Exception e) {
e.printStackTrace();
}
File wsdlFile=new File(output,"exception.wsdl");
assertTrue(wsdlFile.exists());
Document doc=StaxUtils.read(wsdlFile);
Map map=new HashMap();
map.put("xsd","http://www.w3.org/2001/XMLSchema");
map.put("wsdl","http://schemas.xmlsoap.org/wsdl/");
map.put("soap","http://schemas.xmlsoap.org/wsdl/soap/");
XPathUtils util=new XPathUtils(map);
assertNotNull(util.getValueNode("//xsd:complexType[@name='Exception']",doc));
Element nd=(Element)util.getValueNode("//xsd:element[@name='Exception']",doc);
assertNotNull(nd);
assertTrue(nd.getAttribute("type").contains("Exception"));
nd=(Element)util.getValueNode("//xsd:element[@name='message']",doc);
assertNotNull(nd);
assertTrue(nd.getAttribute("type").contains("string"));
assertTrue(nd.getAttribute("minOccurs").contains("0"));
nd=(Element)util.getValueNode("//wsdl:part[@name='Exception']",doc);
assertNotNull(nd);
assertTrue(nd.getAttribute("element").contains(":Exception"));
nd=(Element)util.getValueNode("//wsdl:fault[@name='Exception']",doc);
assertNotNull(nd);
assertTrue(nd.getAttribute("message").contains(":Exception"));
nd=(Element)util.getValueNode("//soap:fault[@name='Exception']",doc);
assertNotNull(nd);
assertTrue(nd.getAttribute("use").contains("literal"));
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetServiceName() throws Exception {
processor.setEnvironment(env);
assertNull(processor.getServiceName());
env.put(ToolConstants.CFG_SERVICENAME,"myservice");
processor.setEnvironment(env);
assertEquals("myservice",processor.getServiceName());
}
APIUtilityVerifier IterativeVerifier BranchVerifier UtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testXmlAccessorOrderInException() throws Exception {
env.put(ToolConstants.CFG_OUTPUTFILE,output.getPath() + "/exception_order.wsdl");
env.put(ToolConstants.CFG_CLASSNAME,"org.apache.cxf.tools.fortest.exception.OrderEchoImpl");
env.put(ToolConstants.CFG_VERBOSE,ToolConstants.CFG_VERBOSE);
try {
processor.setEnvironment(env);
processor.process();
}
catch ( Exception e) {
e.printStackTrace();
}
File wsdlFile=new File(output,"exception_order.wsdl");
assertTrue(wsdlFile.exists());
Document doc=StaxUtils.read(wsdlFile);
Map map=new HashMap();
map.put("xsd","http://www.w3.org/2001/XMLSchema");
map.put("wsdl","http://schemas.xmlsoap.org/wsdl/");
map.put("soap","http://schemas.xmlsoap.org/wsdl/soap/");
XPathUtils util=new XPathUtils(map);
Element summary=(Element)util.getValueNode("//xsd:element[@name='summary']",doc);
Element from=(Element)util.getValueNode("//xsd:element[@name='from']",doc);
Element id=(Element)util.getValueNode("//xsd:element[@name='id']",doc);
assertNotNull(summary);
assertNotNull(from);
assertNotNull(id);
Node nd=from.getNextSibling();
while (nd != null) {
if (nd == id) {
from=null;
}
else if (nd == summary) {
if (from != null) {
fail("from before summary");
}
id=null;
}
nd=nd.getNextSibling();
}
assertNull(id);
assertNull(from);
}
APIUtilityVerifier IterativeVerifier BranchVerifier UtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testPropOrderInException() throws Exception {
env.put(ToolConstants.CFG_OUTPUTFILE,output.getPath() + "/exception_prop_order.wsdl");
env.put(ToolConstants.CFG_CLASSNAME,"org.apache.cxf.tools.fortest.exception.EchoImpl");
env.put(ToolConstants.CFG_VERBOSE,ToolConstants.CFG_VERBOSE);
try {
processor.setEnvironment(env);
processor.process();
}
catch ( Exception e) {
e.printStackTrace();
}
File wsdlFile=new File(output,"exception_prop_order.wsdl");
assertTrue(wsdlFile.exists());
Document doc=StaxUtils.read(wsdlFile);
Map map=new HashMap();
map.put("xsd","http://www.w3.org/2001/XMLSchema");
map.put("wsdl","http://schemas.xmlsoap.org/wsdl/");
map.put("soap","http://schemas.xmlsoap.org/wsdl/soap/");
XPathUtils util=new XPathUtils(map);
Element summary=(Element)util.getValueNode("//xsd:element[@name='summary']",doc);
Element from=(Element)util.getValueNode("//xsd:element[@name='from']",doc);
Element id=(Element)util.getValueNode("//xsd:element[@name='id']",doc);
assertNotNull(summary);
assertNotNull(from);
assertNotNull(id);
Node nd=summary.getNextSibling();
while (nd != null) {
if (nd == from) {
from=null;
}
else if (nd == id) {
if (from != null) {
fail("id before from");
}
id=null;
}
nd=nd.getNextSibling();
}
assertNull(id);
assertNull(from);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testExceptionList() throws Exception {
env.put(ToolConstants.CFG_OUTPUTFILE,output.getPath() + "/exception_list.wsdl");
env.put(ToolConstants.CFG_CLASSNAME,"org.apache.cxf.tools.fortest.exception.Echo2Impl");
env.put(ToolConstants.CFG_VERBOSE,ToolConstants.CFG_VERBOSE);
try {
processor.setEnvironment(env);
processor.process();
}
catch ( Exception e) {
e.printStackTrace();
}
File wsdlFile=new File(output,"exception_list.wsdl");
assertTrue(wsdlFile.exists());
Document doc=StaxUtils.read(wsdlFile);
Map map=new HashMap();
map.put("xsd","http://www.w3.org/2001/XMLSchema");
map.put("wsdl","http://schemas.xmlsoap.org/wsdl/");
map.put("soap","http://schemas.xmlsoap.org/wsdl/soap/");
XPathUtils util=new XPathUtils(map);
Element nd=(Element)util.getValueNode("//xsd:element[@name='names']",doc);
assertNotNull(nd);
assertEquals("0",nd.getAttribute("minOccurs"));
assertEquals("unbounded",nd.getAttribute("maxOccurs"));
assertTrue(nd.getAttribute("type").endsWith(":myData"));
nd=(Element)util.getValueNode("//xsd:complexType[@name='ListException2']" + "/xsd:sequence/xsd:element[@name='address']",doc);
assertNotNull(nd);
assertEquals("0",nd.getAttribute("minOccurs"));
assertEquals("unbounded",nd.getAttribute("maxOccurs"));
assertTrue(nd.getAttribute("type").endsWith(":myData"));
}
Class: org.apache.cxf.tools.java2wsdl.processor.internal.ServiceBuilderFactoryTest BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testGetSimpleBuilder(){
factory.setServiceClass(Hello.class);
ServiceBuilder builder=factory.newBuilder();
assertNotNull(builder);
assertTrue(builder instanceof SimpleServiceBuilder);
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testGetJaxwsBuilder(){
factory.setServiceClass(Stock.class);
ServiceBuilder builder=factory.newBuilder();
assertNotNull(builder);
assertTrue(builder instanceof JaxwsServiceBuilder);
}
Class: org.apache.cxf.tools.java2wsdl.processor.internal.jaxws.FaultBeanTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testTransform() throws Exception {
Class> faultClass=Class.forName("org.apache.cxf.tools.fortest.cxf523.DBServiceFault");
FaultBean bean=new FaultBean();
WrapperBeanClass beanClass=bean.transform(faultClass,"org.apache.cxf.tools.fortest.cxf523.jaxws");
assertNotNull(beanClass);
assertEquals("DBServiceFaultBean",beanClass.getName());
assertEquals("org.apache.cxf.tools.fortest.cxf523.jaxws",beanClass.getPackageName());
assertEquals(1,beanClass.getFields().size());
JavaField field=beanClass.getFields().get(0);
assertEquals("message",field.getName());
assertEquals("java.lang.String",field.getType());
QName qname=beanClass.getElementName();
assertEquals("DBServiceFault",qname.getLocalPart());
assertEquals("http://cxf523.fortest.tools.cxf.apache.org/",qname.getNamespaceURI());
}
Class: org.apache.cxf.tools.java2wsdl.processor.internal.jaxws.JaxwsServiceBuilderTest BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCXF669() throws Exception {
boolean oldSetting=generator.allowImports();
generator.setAllowImports(true);
builder.setServiceClass(org.apache.cxf.tools.fortest.cxf669.HelloImpl.class);
ServiceInfo service=builder.createService();
assertNotNull(service);
assertEquals(new QName("http://foo.com/HelloWorldService","HelloService"),service.getName());
assertEquals(new QName("http://foo.com/HelloWorld","HelloWorld"),service.getInterface().getName());
assertEquals(1,service.getSchemas().size());
assertEquals("http://foo.com/HelloWorld",service.getSchemas().iterator().next().getNamespaceURI());
Collection bindings=service.getBindings();
assertEquals(1,bindings.size());
assertEquals(new QName("http://foo.com/HelloWorldService","HelloServiceSoapBinding"),bindings.iterator().next().getName());
generator.setServiceModel(service);
File wsdl=getOutputFile("HelloService.wsdl");
assertNotNull(wsdl);
generator.generate(wsdl);
assertTrue(wsdl.exists());
File logical=new File(output,"HelloWorld.wsdl");
assertTrue(logical.exists());
File schema=new File(output,"HelloService_schema1.xsd");
assertTrue(schema.exists());
String s=IOUtils.toString(new FileInputStream(wsdl));
assertTrue(s.indexOf("") != -1);
assertTrue(s.indexOf("targetNamespace=\"http://foo.com/HelloWorldService\"") != -1);
s=IOUtils.toString(new FileInputStream(logical));
assertTrue(s.indexOf(" ") != -1);
assertTrue(s.indexOf("targetNamespace=\"http://foo.com/HelloWorld\"") != -1);
s=IOUtils.toString(new FileInputStream(schema));
assertTrue(s.indexOf("targetNamespace=\"http://foo.com/HelloWorld\"") != -1);
generator.setAllowImports(oldSetting);
}
TestInitializer InternalCallVerifier NullVerifier HybridVerifier
@Before public void setUp() throws Exception {
JAXBContextCache.clearCaches();
builder=new JaxwsServiceBuilder();
builder.setBus(BusFactory.getDefaultBus());
generator.setBus(builder.getBus());
generator.setToolContext(new ToolContext());
Bus b=builder.getBus();
assertNotNull(b.getExtension(DestinationFactoryManager.class).getDestinationFactory("http://schemas.xmlsoap.org/soap/http"));
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testRpcLitNoSEI() throws Exception {
builder.setServiceClass(org.apache.cxf.tools.fortest.withannotation.rpc.EchoImpl.class);
ServiceInfo service=builder.createService();
assertNotNull(service);
assertEquals(new QName("http://cxf.apache.org/echotest","EchoService"),service.getName());
assertEquals(new QName("http://cxf.apache.org/echotest","Echo"),service.getInterface().getName());
generator.setServiceModel(service);
File output=getOutputFile("rpclist_no_sei.wsdl");
assertNotNull(output);
generator.generate(output);
assertTrue(output.exists());
String s=IOUtils.toString(new FileInputStream(output));
assertTrue(s.indexOf("EchoPort") != -1);
URI expectedFile=this.getClass().getResource("expected/expected_rpclist_no_sei.wsdl").toURI();
assertWsdlEquals(new File(expectedFile),output);
}
Class: org.apache.cxf.tools.java2wsdl.processor.internal.jaxws.RequestWrapperTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testWithAnnotationNoClass() throws Exception {
String pkgName="org.apache.cxf.tools.fortest.withannotation.doc";
Class> testingClass=Class.forName(pkgName + ".Stock");
OperationInfo opInfo=getOperation(testingClass,"getPrice");
Wrapper wrapper=new RequestWrapper();
wrapper.setOperationInfo(opInfo);
assertFalse(wrapper.isWrapperAbsent());
assertTrue(wrapper.isToDifferentPackage());
assertFalse(wrapper.isWrapperBeanClassNotExist());
assertEquals(pkgName + ".jaxws",wrapper.getJavaClass().getPackageName());
assertEquals("GetPrice",wrapper.getJavaClass().getName());
}
InternalCallVerifier EqualityVerifier
@Test public void testCXF1752() throws Exception {
OperationInfo opInfo=getOperation(AddNumbersPortType.class,"testCXF1752");
RequestWrapper wrapper=new RequestWrapper();
wrapper.setOperationInfo(opInfo);
wrapper.buildWrapperBeanClass();
List fields=wrapper.getJavaClass().getFields();
assertEquals(6,fields.size());
assertEquals("java.util.List",fields.get(0).getClassName());
assertEquals("byte[]",fields.get(2).getClassName());
assertEquals("org.apache.cxf.tools.fortest.xmllist.AddNumbersPortType.UserObject[]",fields.get(3).getClassName());
assertEquals("java.util.List",fields.get(4).getClassName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBuildRequestFields(){
Class> testingClass=GreeterArray.class;
OperationInfo opInfo=getOperation(testingClass,"sayStringArray");
assertNotNull(opInfo);
RequestWrapper requestWrapper=new RequestWrapper();
MessageInfo message=opInfo.getUnwrappedOperation().getInput();
Method method=(Method)opInfo.getProperty("operation.method");
List fields=requestWrapper.buildFields(method,message);
assertEquals(1,fields.size());
JavaField field=fields.get(0);
assertEquals("arg0",field.getName());
assertEquals("String[]",field.getType());
opInfo=getOperation(testingClass,"sayIntArray");
assertNotNull(opInfo);
message=opInfo.getUnwrappedOperation().getInput();
method=(Method)opInfo.getProperty("operation.method");
fields=requestWrapper.buildFields(method,message);
assertEquals(1,fields.size());
field=fields.get(0);
assertEquals("arg0",field.getName());
assertEquals("int[]",field.getType());
opInfo=getOperation(testingClass,"sayTestDataBeanArray");
assertNotNull(opInfo);
message=opInfo.getUnwrappedOperation().getInput();
method=(Method)opInfo.getProperty("operation.method");
fields=requestWrapper.buildFields(method,message);
assertEquals(1,fields.size());
field=fields.get(0);
assertEquals("arg0",field.getName());
assertEquals("org.apache.cxf.tools.fortest.withannotation.doc.TestDataBean[]",field.getType());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testNoAnnotationNoClass() throws Exception {
String pkgName="org.apache.cxf.tools.fortest.classnoanno.docwrapped";
Class> testingClass=Class.forName(pkgName + ".Stock");
OperationInfo opInfo=getOperation(testingClass,"getPrice");
Wrapper wrapper=new RequestWrapper();
wrapper.setOperationInfo(opInfo);
assertTrue(wrapper.isWrapperAbsent());
assertTrue(wrapper.isToDifferentPackage());
assertFalse(wrapper.isWrapperBeanClassNotExist());
assertEquals(pkgName + ".jaxws",wrapper.getJavaClass().getPackageName());
assertEquals("GetPrice",wrapper.getJavaClass().getName());
JavaClass jClass=wrapper.buildWrapperBeanClass();
assertNotNull(jClass);
List jFields=jClass.getFields();
assertEquals(1,jFields.size());
assertEquals("arg0",jFields.get(0).getName());
assertEquals("java.lang.String",jFields.get(0).getClassName());
List jMethods=jClass.getMethods();
assertEquals(2,jMethods.size());
JavaMethod jMethod=jMethods.get(0);
assertEquals("getArg0",jMethod.getName());
assertTrue(jMethod.getParameterListWithoutAnnotation().isEmpty());
jMethod=jMethods.get(1);
assertEquals("setArg0",jMethod.getName());
assertEquals(1,jMethod.getParameterListWithoutAnnotation().size());
assertEquals("java.lang.String newArg0",jMethod.getParameterListWithoutAnnotation().get(0));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testWithAnnotationWithClass() throws Exception {
String pkgName="org.apache.cxf.tools.fortest.withannotation.doc";
Class> testingClass=Class.forName(pkgName + ".Greeter");
OperationInfo opInfo=getOperation(testingClass,"sayHi");
Wrapper wrapper=new RequestWrapper();
wrapper.setOperationInfo(opInfo);
assertFalse(wrapper.isWrapperAbsent());
assertTrue(wrapper.isToDifferentPackage());
assertFalse(wrapper.isWrapperBeanClassNotExist());
assertEquals(pkgName,wrapper.getJavaClass().getPackageName());
assertEquals("SayHi",wrapper.getJavaClass().getName());
}
Class: org.apache.cxf.tools.java2wsdl.processor.internal.jaxws.ResponseWrapperTest InternalCallVerifier EqualityVerifier
@Test public void testWithAnnotationWithClass() throws Exception {
String pkgName="org.apache.cxf.tools.fortest.withannotation.doc";
Class> testingClass=Class.forName(pkgName + ".Greeter");
OperationInfo opInfo=getOperation(testingClass,"sayHi");
Wrapper wrapper=new ResponseWrapper();
wrapper.setOperationInfo(opInfo);
assertEquals(pkgName,wrapper.getJavaClass().getPackageName());
assertEquals("SayHiResponse",wrapper.getJavaClass().getName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBuildFields(){
Class> testingClass=GreeterArray.class;
OperationInfo opInfo=getOperation(testingClass,"sayStringArray");
assertNotNull(opInfo);
ResponseWrapper responseWrapper=new ResponseWrapper();
MessageInfo message=opInfo.getUnwrappedOperation().getOutput();
Method method=(Method)opInfo.getProperty("operation.method");
JavaField field=responseWrapper.buildFields(method,message).get(0);
assertEquals("_return",field.getParaName());
assertEquals("String[]",field.getType());
opInfo=getOperation(testingClass,"sayIntArray");
assertNotNull(opInfo);
message=opInfo.getUnwrappedOperation().getOutput();
method=(Method)opInfo.getProperty("operation.method");
field=responseWrapper.buildFields(method,message).get(0);
assertEquals("_return",field.getParaName());
assertEquals("int[]",field.getType());
opInfo=getOperation(testingClass,"sayTestDataBeanArray");
assertNotNull(opInfo);
message=opInfo.getUnwrappedOperation().getOutput();
method=(Method)opInfo.getProperty("operation.method");
field=responseWrapper.buildFields(method,message).get(0);
assertEquals("_return",field.getParaName());
assertEquals("org.apache.cxf.tools.fortest.withannotation.doc.TestDataBean[]",field.getType());
}
Class: org.apache.cxf.tools.java2wsdl.processor.internal.jaxws.WrapperTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testIsWrapperBeanClassNotExist() throws Exception {
String pkgName="org.apache.cxf.tools.fortest.classnoanno.docwrapped";
Class> stockClass=Class.forName(pkgName + ".Stock");
Method method=stockClass.getMethod("getPrice",String.class);
Wrapper wrapper=new RequestWrapper();
wrapper.setMethod(method);
assertTrue(wrapper.isWrapperAbsent());
assertTrue(wrapper.isToDifferentPackage());
assertFalse(wrapper.isWrapperBeanClassNotExist());
assertEquals(pkgName + ".jaxws",wrapper.getJavaClass().getPackageName());
assertEquals("GetPrice",wrapper.getJavaClass().getName());
pkgName="org.apache.cxf.tools.fortest.withannotation.doc";
stockClass=Class.forName(pkgName + ".Stock");
method=stockClass.getMethod("getPrice",String.class);
wrapper=new RequestWrapper();
wrapper.setMethod(method);
assertFalse(wrapper.isWrapperAbsent());
assertTrue(wrapper.isToDifferentPackage());
assertFalse(wrapper.isWrapperBeanClassNotExist());
assertEquals(pkgName + ".jaxws",wrapper.getJavaClass().getPackageName());
assertEquals("GetPrice",wrapper.getJavaClass().getName());
pkgName="org.apache.cxf.tools.fortest.withannotation.doc";
Class> clz=Class.forName(pkgName + ".Greeter");
method=clz.getMethod("sayHi");
wrapper=new RequestWrapper();
wrapper.setMethod(method);
assertFalse(wrapper.isWrapperAbsent());
assertTrue(wrapper.isToDifferentPackage());
assertFalse(wrapper.isWrapperBeanClassNotExist());
assertEquals(pkgName,wrapper.getJavaClass().getPackageName());
assertEquals("SayHi",wrapper.getJavaClass().getName());
wrapper=new ResponseWrapper();
wrapper.setMethod(method);
assertEquals(pkgName,wrapper.getJavaClass().getPackageName());
assertEquals("SayHiResponse",wrapper.getJavaClass().getName());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetWrapperBeanClassFromQName(){
QName qname=new QName("http://cxf.apache.org","sayHi");
Wrapper wrapper=new Wrapper();
wrapper.setName(qname);
JavaClass jClass=wrapper.getWrapperBeanClass(qname);
assertEquals("org.apache.cxf",jClass.getPackageName());
assertEquals("SayHi",jClass.getName());
assertEquals("http://cxf.apache.org",jClass.getNamespace());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetWrapperBeanClassFromMethod() throws Exception {
String pkgName="org.apache.cxf.tools.fortest.classnoanno.docwrapped";
Class> stockClass=Class.forName(pkgName + ".Stock");
Method method=stockClass.getMethod("getPrice",String.class);
Wrapper wrapper=new Wrapper();
wrapper.setMethod(method);
JavaClass jClass=wrapper.getWrapperBeanClass(method);
assertNotNull(jClass);
assertNull(jClass.getPackageName());
assertNull(jClass.getName());
wrapper=new RequestWrapper();
jClass=wrapper.getWrapperBeanClass(method);
assertEquals("GetPrice",jClass.getName());
assertEquals(pkgName + ".jaxws",jClass.getPackageName());
wrapper=new ResponseWrapper();
jClass=wrapper.getWrapperBeanClass(method);
assertEquals("GetPriceResponse",jClass.getName());
assertEquals(pkgName + ".jaxws",jClass.getPackageName());
}
Class: org.apache.cxf.tools.misc.processor.WSDLToServiceProcessorTest APIUtilityVerifier IterativeVerifier BranchVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testNewServiceSoap12() throws Exception {
String[] args=new String[]{"-soap12","-transport","soap","-e","SOAPService","-p","SoapPort","-n","Greeter_SOAPBinding","-a","http://localhost:9000/SOAPService/SoapPort","-d",output.getCanonicalPath(),getLocation("/misctools_wsdl/hello_world_soap12.wsdl")};
WSDLToService.main(args);
File outputFile=new File(output,"hello_world_soap12-service.wsdl");
assertTrue("New wsdl file is not generated",outputFile.exists());
WSDLToServiceProcessor processor=new WSDLToServiceProcessor();
processor.setEnvironment(env);
try {
processor.parseWSDL(outputFile.getAbsolutePath());
Service service=processor.getWSDLDefinition().getService(new QName(processor.getWSDLDefinition().getTargetNamespace(),"SOAPService"));
if (service == null) {
fail("Element wsdl:service serviceins Missed!");
}
Iterator> it=service.getPort("SoapPort").getExtensibilityElements().iterator();
if (it == null || !it.hasNext()) {
fail("Element wsdl:port portins Missed!");
}
while (it.hasNext()) {
Object obj=it.next();
if (obj instanceof SOAP12Address) {
SOAP12Address soapAddress=(SOAP12Address)obj;
assertNotNull(soapAddress.getLocationURI());
assertEquals("http://localhost:9000/SOAPService/SoapPort",soapAddress.getLocationURI());
break;
}
}
}
catch ( ToolException e) {
fail("Exception Encountered when parsing wsdl, error: " + e.getMessage());
}
}
Class: org.apache.cxf.tools.misc.processor.WSDLToSoapProcessorTest APIUtilityVerifier BranchVerifier UtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testNewSoap12Binding() throws Exception {
String[] args=new String[]{"-i","Greeter","-soap12","-b","Greeter_SOAP12Binding","-d",output.getCanonicalPath(),"-o","hello_world_soap12_newbinding.wsdl",getLocation("/misctools_wsdl/hello_world_soap12_nobinding.wsdl")};
WSDLToSoap.main(args);
File outputFile=new File(output,"hello_world_soap12_newbinding.wsdl");
assertTrue("New wsdl file is not generated",outputFile.exists());
assertTrue("Generated file is empty!",outputFile.length() > 0);
WSDLToSoapProcessor processor=new WSDLToSoapProcessor();
processor.setEnvironment(env);
try {
processor.parseWSDL(outputFile.getAbsolutePath());
Binding binding=processor.getWSDLDefinition().getBinding(new QName(processor.getWSDLDefinition().getTargetNamespace(),"Greeter_SOAP12Binding"));
if (binding == null) {
fail("Element wsdl:binding Greeter_SOAPBinding_NewBinding Missed!");
}
for ( Object obj : binding.getExtensibilityElements()) {
assertTrue(SOAPBindingUtil.isSOAPBinding(obj));
assertTrue(obj instanceof SOAP12Binding);
SoapBinding soapBinding=SOAPBindingUtil.getSoapBinding(obj);
assertNotNull(soapBinding);
assertTrue("document".equalsIgnoreCase(soapBinding.getStyle()));
assertTrue(WSDLConstants.NS_SOAP_HTTP_TRANSPORT.equalsIgnoreCase(soapBinding.getTransportURI()));
}
BindingOperation bo=binding.getBindingOperation("sayHi",null,null);
if (bo == null) {
fail("Element Missed!");
}
for ( Object obj : bo.getExtensibilityElements()) {
assertTrue(SOAPBindingUtil.isSOAPOperation(obj));
assertTrue(obj instanceof SOAP12Operation);
SoapOperation soapOperation=SOAPBindingUtil.getSoapOperation(obj);
assertNotNull(soapOperation);
assertTrue("document".equalsIgnoreCase(soapOperation.getStyle()));
}
BindingInput bi=bo.getBindingInput();
for ( Object obj : bi.getExtensibilityElements()) {
assertTrue(SOAPBindingUtil.isSOAPBody(obj));
assertTrue(obj instanceof SOAP12Body);
SoapBody soapBody=SOAPBindingUtil.getSoapBody(obj);
assertNotNull(soapBody);
assertTrue("literal".equalsIgnoreCase(soapBody.getUse()));
}
}
catch ( ToolException e) {
fail("Exception Encountered when parsing wsdl, error: " + e.getMessage());
}
}
APIUtilityVerifier BranchVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testDocLitWithFault() throws Exception {
String[] args=new String[]{"-i","Greeter","-d",output.getCanonicalPath(),getLocation("/misctools_wsdl/hello_world_doc_lit.wsdl")};
WSDLToSoap.main(args);
File outputFile=new File(output,"hello_world_doc_lit-soapbinding.wsdl");
assertTrue("New wsdl file is not generated",outputFile.exists());
WSDLToSoapProcessor processor=new WSDLToSoapProcessor();
processor.setEnvironment(env);
try {
processor.parseWSDL(outputFile.getAbsolutePath());
Binding binding=processor.getWSDLDefinition().getBinding(new QName(processor.getWSDLDefinition().getTargetNamespace(),"Greeter_Binding"));
if (binding == null) {
fail("Element wsdl:binding Greeter_Binding Missed!");
}
boolean found=false;
for ( Object obj : binding.getExtensibilityElements()) {
SoapBinding soapBinding=SOAPBindingUtil.getSoapBinding(obj);
if (soapBinding != null && soapBinding.getStyle().equalsIgnoreCase("document")) {
found=true;
break;
}
}
if (!found) {
fail("Element soap:binding Missed!");
}
BindingOperation bo=binding.getBindingOperation("pingMe",null,null);
if (bo == null) {
fail("Element Missed!");
}
found=false;
for ( Object obj : bo.getExtensibilityElements()) {
SoapOperation soapOperation=SOAPBindingUtil.getSoapOperation(obj);
if (soapOperation != null && soapOperation.getStyle().equalsIgnoreCase("document")) {
found=true;
break;
}
}
if (!found) {
fail("Element soap:operation Missed!");
}
BindingFault fault=bo.getBindingFault("pingMeFault");
if (fault == null) {
fail("Element Missed!");
}
found=false;
for ( Object obj : fault.getExtensibilityElements()) {
if (SOAPBindingUtil.isSOAPFault(obj)) {
found=true;
break;
}
}
if (!found) {
fail("Element soap:fault Missed!");
}
List faults=SOAPBindingUtil.getBindingOperationSoapFaults(bo);
assertEquals(1,faults.size());
assertEquals("pingMeFault",faults.get(0).getName());
}
catch ( ToolException e) {
fail("Exception Encountered when parsing wsdl, error: " + e.getMessage());
}
}
APIUtilityVerifier BranchVerifier UtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testWithoutBinding() throws Exception {
String[] args=new String[]{"-i","Greeter","-b","Greeter_SOAPBinding","-d",output.getCanonicalPath(),"-o","hello_world_soap_newbinding.wsdl",getLocation("/misctools_wsdl/hello_world_nobinding.wsdl")};
WSDLToSoap.main(args);
File outputFile=new File(output,"hello_world_soap_newbinding.wsdl");
assertTrue("New wsdl file is not generated",outputFile.exists());
assertTrue("Generated file is empty!",outputFile.length() > 0);
WSDLToSoapProcessor processor=new WSDLToSoapProcessor();
processor.setEnvironment(env);
try {
processor.parseWSDL(outputFile.getAbsolutePath());
Binding binding=processor.getWSDLDefinition().getBinding(new QName(processor.getWSDLDefinition().getTargetNamespace(),"Greeter_SOAPBinding"));
if (binding == null) {
fail("Element wsdl:binding Greeter_SOAPBinding_NewBinding Missed!");
}
for ( Object obj : binding.getExtensibilityElements()) {
assertTrue(SOAPBindingUtil.isSOAPBinding(obj));
assertTrue(obj instanceof SOAPBinding);
SoapBinding soapBinding=SOAPBindingUtil.getSoapBinding(obj);
assertNotNull(soapBinding);
assertTrue("document".equalsIgnoreCase(soapBinding.getStyle()));
assertTrue(WSDLConstants.NS_SOAP11_HTTP_TRANSPORT.equalsIgnoreCase(soapBinding.getTransportURI()));
}
BindingOperation bo=binding.getBindingOperation("sayHi",null,null);
if (bo == null) {
fail("Element Missed!");
}
for ( Object obj : bo.getExtensibilityElements()) {
assertTrue(SOAPBindingUtil.isSOAPOperation(obj));
assertTrue(obj instanceof SOAPOperation);
SoapOperation soapOperation=SOAPBindingUtil.getSoapOperation(obj);
assertNotNull(soapOperation);
assertTrue("document".equalsIgnoreCase(soapOperation.getStyle()));
}
BindingInput bi=bo.getBindingInput();
for ( Object obj : bi.getExtensibilityElements()) {
assertTrue(SOAPBindingUtil.isSOAPBody(obj));
assertTrue(obj instanceof SOAPBody);
SoapBody soapBody=SOAPBindingUtil.getSoapBody(obj);
assertNotNull(soapBody);
assertTrue("literal".equalsIgnoreCase(soapBody.getUse()));
}
}
catch ( ToolException e) {
fail("Exception Encountered when parsing wsdl, error: " + e.getMessage());
}
}
APIUtilityVerifier BranchVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testAddSoap12Binding() throws Exception {
String[] args=new String[]{"-i","Greeter","-soap12","-b","Greeter_SOAP12Binding","-d",output.getCanonicalPath(),"-o","hello_world_soap12_newbinding.wsdl",getLocation("/misctools_wsdl/hello_world_soap12.wsdl")};
WSDLToSoap.main(args);
File outputFile=new File(output,"hello_world_soap12_newbinding.wsdl");
assertTrue("New wsdl file is not generated",outputFile.exists());
WSDLToSoapProcessor processor=new WSDLToSoapProcessor();
processor.setEnvironment(env);
try {
processor.parseWSDL(outputFile.getAbsolutePath());
Binding binding=processor.getWSDLDefinition().getBinding(new QName(processor.getWSDLDefinition().getTargetNamespace(),"Greeter_SOAP12Binding"));
if (binding == null) {
fail("Element wsdl:binding Greeter_SOAPBinding_NewBinding Missed!");
}
for ( Object obj : binding.getExtensibilityElements()) {
assertTrue(SOAPBindingUtil.isSOAPBinding(obj));
assertTrue(obj instanceof SOAP12Binding);
SoapBinding soapBinding=SOAPBindingUtil.getSoapBinding(obj);
assertNotNull(soapBinding);
assertTrue("document".equalsIgnoreCase(soapBinding.getStyle()));
}
BindingOperation bo=binding.getBindingOperation("sayHi",null,null);
if (bo == null) {
fail("Element Missed!");
}
for ( Object obj : bo.getExtensibilityElements()) {
assertTrue(SOAPBindingUtil.isSOAPOperation(obj));
assertTrue(obj instanceof SOAP12Operation);
SoapOperation soapOperation=SOAPBindingUtil.getSoapOperation(obj);
assertNotNull(soapOperation);
assertTrue("document".equalsIgnoreCase(soapOperation.getStyle()));
}
BindingInput bi=bo.getBindingInput();
for ( Object obj : bi.getExtensibilityElements()) {
assertTrue(SOAPBindingUtil.isSOAPBody(obj));
assertTrue(obj instanceof SOAP12Body);
SoapBody soapBody=SOAPBindingUtil.getSoapBody(obj);
assertNotNull(soapBody);
assertTrue("literal".equalsIgnoreCase(soapBody.getUse()));
}
bo=binding.getBindingOperation("pingMe",null,null);
assertNotNull(bo);
Iterator> it=bo.getExtensibilityElements().iterator();
assertTrue(it != null && it.hasNext());
assertTrue(it.next() instanceof SOAP12Operation);
it=bo.getBindingInput().getExtensibilityElements().iterator();
assertTrue(it != null && it.hasNext());
assertTrue(it.next() instanceof SOAP12Body);
it=bo.getBindingOutput().getExtensibilityElements().iterator();
assertTrue(it != null && it.hasNext());
assertTrue(it.next() instanceof SOAP12Body);
Map,?> faults=bo.getBindingFaults();
assertTrue(faults != null && faults.size() == 1);
Object bf=faults.get("pingMeFault");
assertNotNull(bf);
assertTrue(bf instanceof BindingFault);
assertEquals("pingMeFault",((BindingFault)bf).getName());
}
catch ( ToolException e) {
fail("Exception Encountered when parsing wsdl, error: " + e.getMessage());
}
}
Class: org.apache.cxf.tools.util.StAXUtilTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetTags() throws Exception {
File file=new File(getClass().getResource("resources/test.wsdl").toURI());
file=getResource("resources/test2.wsdl");
Tag tag1=ToolsStaxUtils.getTagTree(file);
assertEquals(1,tag1.getTags().size());
Tag def1=tag1.getTags().get(0);
assertEquals(6,def1.getTags().size());
Tag types1=def1.getTags().get(0);
Tag schema1=types1.getTags().get(0);
assertEquals(4,schema1.getTags().size());
file=getResource("resources/test3.wsdl");
Tag tag2=ToolsStaxUtils.getTagTree(file);
assertEquals(1,tag2.getTags().size());
Tag def2=tag2.getTags().get(0);
assertEquals(6,def2.getTags().size());
Tag types2=def2.getTags().get(0);
Tag schema2=types2.getTags().get(0);
assertEquals(4,schema2.getTags().size());
assertTagEquals(schema1,schema2);
}
Class: org.apache.cxf.tools.validator.internal.WSDL11ValidatorTest BooleanVerifier InternalCallVerifier
@Test public void testWSDLImport() throws Exception {
String wsdlSource=getClass().getResource("resources/a.wsdl").toURI().toString();
context.put(ToolConstants.CFG_WSDLURL,wsdlSource);
WSDL11Validator validator=new WSDL11Validator(null,context);
try {
assertFalse(validator.isValid());
}
catch ( Exception e) {
assertTrue(e.getMessage(),e.getMessage().indexOf("Caused by {http://apache.org/hello_world/messages}" + "[portType:GreeterA][operation:sayHi] not exist.") != -1);
}
}
Class: org.apache.cxf.tools.validator.internal.WSDLRefValidatorTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testLogicalWSDL() throws Exception {
String wsdl=getClass().getResource("resources/logical.wsdl").toURI().toString();
WSDLRefValidator validator=new WSDLRefValidator(getWSDL(wsdl),null);
validator.isValid();
ValidationResult results=validator.getValidationResults();
assertEquals(1,results.getErrors().size());
String text="{http://schemas.apache.org/yoko/idl/OptionsPT}[message:getEmployee]";
Set possibles=new HashSet();
possibles.add(new Message("FAILED_AT_POINT",WSDLRefValidator.LOG,42,6,new java.net.URI(wsdl).toURL(),text).toString());
possibles.add(new Message("FAILED_AT_POINT",WSDLRefValidator.LOG,42,70,new java.net.URI(wsdl).toURL(),text).toString());
possibles.add(new Message("FAILED_AT_POINT",WSDLRefValidator.LOG,-1,-1,new java.net.URI(wsdl).toURL(),text).toString());
assertTrue(possibles.contains(results.getErrors().pop()));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testNoTypeRef() throws Exception {
String wsdl=getClass().getResource("resources/NoTypeRef.wsdl").toURI().toString();
WSDLRefValidator validator=new WSDLRefValidator(getWSDL(wsdl),null);
assertFalse(validator.isValid());
assertEquals(3,validator.getValidationResults().getErrors().size());
String expected="Part in Message " + "<{http://apache.org/samples/headers}inHeaderRequest>" + " referenced Type <{http://apache.org/samples/headers}SOAPHeaderInfo> "+ "can not be found in the schemas";
String t=null;
while (!validator.getValidationResults().getErrors().empty()) {
t=validator.getValidationResults().getErrors().pop();
if (expected.equals(t)) {
break;
}
}
assertEquals(expected,t);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testWSDLImport1() throws Exception {
String wsdl=getClass().getResource("resources/a.wsdl").toURI().toString();
WSDLRefValidator validator=new WSDLRefValidator(getWSDL(wsdl),null);
validator.isValid();
ValidationResult results=validator.getValidationResults();
assertEquals(2,results.getErrors().size());
String t=results.getErrors().pop();
String text="{http://apache.org/hello_world/messages}[portType:GreeterA][operation:sayHi]";
Set possibles=new HashSet();
possibles.add(new Message("FAILED_AT_POINT",WSDLRefValidator.LOG,27,2,new java.net.URI(wsdl).toURL(),text).toString());
possibles.add(new Message("FAILED_AT_POINT",WSDLRefValidator.LOG,27,31,new java.net.URI(wsdl).toURL(),text).toString());
possibles.add(new Message("FAILED_AT_POINT",WSDLRefValidator.LOG,-1,-1,new java.net.URI(wsdl).toURL(),text).toString());
assertTrue(possibles.contains(t));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testNoService() throws Exception {
String wsdl=getClass().getResource("resources/b.wsdl").toURI().toString();
WSDLRefValidator validator=new WSDLRefValidator(getWSDL(wsdl),null);
assertFalse(validator.isValid());
ValidationResult results=validator.getValidationResults();
assertEquals(0,results.getWarnings().size());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testNoBindingWSDL() throws Exception {
String wsdl=getClass().getResource("resources/nobinding.wsdl").toURI().toString();
WSDLRefValidator validator=new WSDLRefValidator(getWSDL(wsdl),null);
validator.isValid();
ValidationResult results=validator.getValidationResults();
assertEquals(0,results.getWarnings().size());
WSDLRefValidator v=new WSDLRefValidator(getWSDL(wsdl),null);
v.setSuppressWarnings(true);
assertTrue(v.isValid());
}
Class: org.apache.cxf.tools.validator.internal.model.XNodeTest InternalCallVerifier EqualityVerifier
@Test public void testGetXPath(){
XNode node=new XNode();
node.setQName(WSDLConstants.QNAME_BINDING);
node.setPrefix("wsdl");
node.setAttributeName("name");
node.setAttributeValue("SOAPBinding");
assertEquals("/wsdl:binding[@name='SOAPBinding']",node.toString());
assertEquals("[binding:SOAPBinding]",node.getPlainText());
}
InternalCallVerifier EqualityVerifier
@Test public void testParentNode(){
XDef definition=new XDef();
String ns="{http://apache.org/hello_world/messages}";
definition.setTargetNamespace("http://apache.org/hello_world/messages");
assertEquals(ns,definition.getPlainText());
XPortType portType=new XPortType();
portType.setName("Greeter");
portType.setParentNode(definition);
String portTypeText=ns + "[portType:Greeter]";
assertEquals(portTypeText,portType.getPlainText());
XOperation op=new XOperation();
op.setName("sayHi");
op.setParentNode(portType);
assertEquals(portTypeText + "[operation:sayHi]",op.getPlainText());
String expected="/wsdl:definitions[@targetNamespace='http://apache.org/hello_world/messages']";
expected+="/wsdl:portType[@name='Greeter']/wsdl:operation[@name='sayHi']";
assertEquals(expected,op.toString());
}
Class: org.apache.cxf.tools.wadlto.jaxrs.JAXRSContainerTest APIUtilityVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testQueryMultipartParam(){
try {
JAXRSContainer container=new JAXRSContainer(null);
ToolContext context=new ToolContext();
context.put(WadlToolConstants.CFG_OUTPUTDIR,output.getCanonicalPath());
context.put(WadlToolConstants.CFG_WADLURL,getLocation("/wadl/testQueryMultipartParam.wadl"));
context.put(WadlToolConstants.CFG_COMPILE,"true");
container.setContext(context);
container.execute();
assertNotNull(output.list());
List files=FileUtils.getFilesRecurse(output,".+\\." + "class" + "$");
assertEquals(2,files.size());
assertTrue(checkContains(files,"application.Test1.class"));
assertTrue(checkContains(files,"application.Test2.class"));
@SuppressWarnings("resource") ClassLoader loader=new URLClassLoader(new URL[]{output.toURI().toURL()});
Class> test1=loader.loadClass("application.Test1");
Method[] test1Methods=test1.getDeclaredMethods();
assertEquals(1,test1Methods.length);
assertEquals(2,test1Methods[0].getAnnotations().length);
assertNotNull(test1Methods[0].getAnnotation(PUT.class));
Consumes consumes1=test1Methods[0].getAnnotation(Consumes.class);
assertNotNull(consumes1);
assertEquals(1,consumes1.value().length);
assertEquals("multipart/mixed",consumes1.value()[0]);
assertEquals("put",test1Methods[0].getName());
Class>[] paramTypes=test1Methods[0].getParameterTypes();
assertEquals(3,paramTypes.length);
Annotation[][] paramAnns=test1Methods[0].getParameterAnnotations();
assertEquals(Boolean.class,paramTypes[0]);
assertEquals(1,paramAnns[0].length);
QueryParam test1QueryParam1=(QueryParam)paramAnns[0][0];
assertEquals("standalone",test1QueryParam1.value());
assertEquals(String.class,paramTypes[1]);
assertEquals(1,paramAnns[1].length);
Multipart test1MultipartParam1=(Multipart)paramAnns[1][0];
assertEquals("action",test1MultipartParam1.value());
assertTrue(test1MultipartParam1.required());
assertEquals(String.class,paramTypes[2]);
assertEquals(1,paramAnns[2].length);
Multipart test1MultipartParam2=(Multipart)paramAnns[2][0];
assertEquals("sources",test1MultipartParam2.value());
assertFalse(test1MultipartParam2.required());
Class> test2=loader.loadClass("application.Test2");
Method[] test2Methods=test2.getDeclaredMethods();
assertEquals(1,test2Methods.length);
assertEquals(2,test2Methods[0].getAnnotations().length);
assertNotNull(test2Methods[0].getAnnotation(PUT.class));
Consumes consumes2=test2Methods[0].getAnnotation(Consumes.class);
assertNotNull(consumes2);
assertEquals(1,consumes2.value().length);
assertEquals("application/json",consumes2.value()[0]);
assertEquals("put",test2Methods[0].getName());
Class>[] paramTypes2=test2Methods[0].getParameterTypes();
assertEquals(2,paramTypes2.length);
Annotation[][] paramAnns2=test2Methods[0].getParameterAnnotations();
assertEquals(boolean.class,paramTypes2[0]);
assertEquals(1,paramAnns2[0].length);
QueryParam test2QueryParam1=(QueryParam)paramAnns2[0][0];
assertEquals("snapshot",test2QueryParam1.value());
assertEquals(String.class,paramTypes2[1]);
assertEquals(0,paramAnns2[1].length);
}
catch ( Exception e) {
e.printStackTrace();
fail();
}
}
Class: org.apache.cxf.tools.wadlto.jaxrs.ValidateWadlTest UtilityVerifier BooleanVerifier InternalCallVerifier HybridVerifier
@Test public void testInvalidParameterStyle() throws Exception {
try {
JAXRSContainer container=new JAXRSContainer(null);
ToolContext context=new ToolContext();
context.put(WadlToolConstants.CFG_WADLURL,getLocation("/wadl/invalidParamStyle.xml"));
container.setContext(context);
container.execute();
fail();
}
catch ( ValidationException e) {
String message=e.getMessage();
assertTrue(message.startsWith("Unsupported parameter style: plain"));
}
}
Class: org.apache.cxf.tools.wsdlto.WSDLToJavaContainerTest BooleanVerifier InternalCallVerifier
@Test public void testWsdlLocationDefaultSchemeIsFile() throws Exception {
WSDLToJavaContainer container=new WSDLToJavaContainer("dummy",null);
ToolContext context=new ToolContext();
context.put(ToolConstants.CFG_WSDLURL,getLocation("hello_world.wsdl"));
container.setContext(context);
container.validate(context);
String wsdlLocation=(String)context.get(ToolConstants.CFG_WSDLLOCATION);
assertTrue("default scheme for wsdlLocation is file",wsdlLocation.startsWith("file:"));
}
UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testValidateorSuppressWarningsIsOn() throws Exception {
WSDLToJavaContainer container=new WSDLToJavaContainer("dummy",null);
ToolContext context=new ToolContext();
context.put(ToolConstants.CFG_WSDLURL,getLocation("hello_world.wsdl"));
container.setContext(context);
try {
container.execute();
}
catch ( ToolException te) {
assertEquals(getLogMessage("FOUND_NO_FRONTEND"),te.getMessage());
}
catch ( Exception e) {
fail("Should not throw any exception but ToolException.");
}
assertTrue(context.optionSet(ToolConstants.CFG_SUPPRESS_WARNINGS));
}
Class: org.apache.cxf.tools.wsdlto.WSDLToJavaTest BooleanVerifier InternalCallVerifier
@Test public void testIsVerbose(){
WSDLToJava w2j=new WSDLToJava();
w2j.setArguments(new String[]{"-V"});
assertTrue(w2j.isVerbose());
w2j=new WSDLToJava();
w2j.setArguments(new String[]{"-verbose"});
assertTrue(w2j.isVerbose());
w2j=new WSDLToJava();
w2j.setArguments(new String[]{"none"});
assertFalse(w2j.isVerbose());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetFrontEndName() throws Exception {
WSDLToJava w2j=new WSDLToJava();
assertEquals("jaxws",w2j.getFrontEndName(new String[]{"-frontend","jaxws"}));
assertEquals("jaxws",w2j.getFrontEndName(new String[]{"-fe","jaxws"}));
assertNull(w2j.getFrontEndName(new String[]{"-frontend"}));
assertNull(w2j.getFrontEndName(new String[]{"-fe"}));
assertNull(w2j.getFrontEndName(new String[]{"nothing"}));
assertNull(w2j.getFrontEndName(null));
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetDataBindingName() throws Exception {
WSDLToJava w2j=new WSDLToJava();
assertEquals("jaxb",w2j.getDataBindingName(new String[]{"-databinding","jaxb"}));
assertEquals("jaxb",w2j.getDataBindingName(new String[]{"-db","jaxb"}));
assertNull(w2j.getDataBindingName(new String[]{"-databinding"}));
assertNull(w2j.getDataBindingName(new String[]{"-db"}));
assertNull(w2j.getDataBindingName(new String[]{"nothing"}));
assertNull(w2j.getDataBindingName(null));
assertNull(w2j.getDataBindingName(new String[]{"-frontend","jaxws"}));
}
Class: org.apache.cxf.tools.wsdlto.core.AbstractGeneratorTest InternalCallVerifier NullVerifier
@Test public void testOverwrite() throws Exception {
gen=new DummyGenerator();
util=new FileWriterUtil(output.toString(),null);
context=new ToolContext();
context.put(ToolConstants.CFG_OUTPUTDIR,output.toString());
gen.setEnvironment(context);
Writer writer=util.getWriter(packageName,className + ".java");
writer.write("hello world");
writer.flush();
writer.close();
assertNotNull(gen.parseOutputName(packageName,className));
}
InternalCallVerifier NullVerifier
@Test public void testKeep() throws Exception {
gen=new DummyGenerator();
util=new FileWriterUtil(output.toString(),null);
context=new ToolContext();
context.put(ToolConstants.CFG_OUTPUTDIR,output.toString());
gen.setEnvironment(context);
Writer writer=util.getWriter(packageName,className + ".java");
writer.write("hello world");
writer.flush();
writer.close();
context.put(ToolConstants.CFG_GEN_NEW_ONLY,"keep");
assertNull(gen.parseOutputName(packageName,className));
}
Class: org.apache.cxf.tools.wsdlto.core.PluginLoaderTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testLoadPlugins() throws Exception {
PluginLoader loader=PluginLoader.getInstance();
assertEquals(4,loader.getPlugins().size());
Plugin plugin=getPlugin(loader,0);
assertNotNull(plugin.getName());
Map frontends=loader.getFrontEnds();
assertNotNull(frontends);
assertEquals(3,frontends.size());
FrontEnd frontend=getFrontEnd(frontends,0);
assertEquals("jaxws",frontend.getName());
assertEquals("org.apache.cxf.tools.wsdlto.frontend.jaxws",frontend.getPackage());
assertEquals("JAXWSProfile",frontend.getProfile());
assertNotNull(frontend.getGenerators());
assertNotNull(frontend.getGenerators().getGenerator());
assertEquals("AntGenerator",getGenerator(frontend,0).getName());
assertEquals("JAXWSContainer",frontend.getContainer().getName());
assertEquals("jaxws-toolspec.xml",frontend.getContainer().getToolspec());
loader.getFrontEndProfile("jaxws");
Map databindings=loader.getDataBindings();
assertNotNull(databindings);
assertEquals(6,databindings.size());
DataBinding databinding=databindings.get("jaxb");
assertNotNull(databinding);
assertEquals("jaxb",databinding.getName());
assertEquals("org.apache.cxf.tools.wsdlto.databinding.jaxb",databinding.getPackage());
assertEquals("JAXBDataBinding",databinding.getProfile());
}
Class: org.apache.cxf.tools.wsdlto.core.WSDLDefinitionBuilderTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBuildSimpleWSDL() throws Exception {
String qname="http://apache.org/hello_world_soap_http";
String wsdlUrl=getClass().getResource("hello_world.wsdl").toString();
WSDLDefinitionBuilder builder=new WSDLDefinitionBuilder(BusFactory.getDefaultBus());
Definition def=builder.build(wsdlUrl);
assertNotNull(def);
Map,?> services=def.getServices();
assertNotNull(services);
assertEquals(1,services.size());
Service service=(Service)services.get(new QName(qname,"SOAPService"));
assertNotNull(service);
Map,?> ports=service.getPorts();
assertNotNull(ports);
assertEquals(1,ports.size());
Port port=service.getPort("SoapPort");
assertNotNull(port);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBuildImportedWSDL() throws Exception {
String wsdlUrl=getClass().getResource("hello_world_services.wsdl").toString();
WSDLDefinitionBuilder builder=new WSDLDefinitionBuilder(BusFactory.getDefaultBus());
Definition def=builder.build(wsdlUrl);
assertNotNull(def);
Map,?> services=def.getServices();
assertNotNull(services);
assertEquals(1,services.size());
String serviceQName="http://apache.org/hello_world/services";
Service service=(Service)services.get(new QName(serviceQName,"SOAPService"));
assertNotNull(service);
Map,?> ports=service.getPorts();
assertNotNull(ports);
assertEquals(1,ports.size());
Port port=service.getPort("SoapPort");
assertNotNull(port);
Binding binding=port.getBinding();
assertNotNull(binding);
QName bindingQName=new QName("http://apache.org/hello_world/bindings","SOAPBinding");
assertEquals(bindingQName,binding.getQName());
PortType portType=binding.getPortType();
assertNotNull(portType);
QName portTypeQName=new QName("http://apache.org/hello_world","Greeter");
assertEquals(portTypeQName,portType.getQName());
Operation op1=portType.getOperation("sayHi","sayHiRequest","sayHiResponse");
assertNotNull(op1);
QName messageQName=new QName("http://apache.org/hello_world/messages","sayHiRequest");
assertEquals(messageQName,op1.getInput().getMessage().getQName());
Part part=op1.getInput().getMessage().getPart("in");
assertNotNull(part);
assertEquals(new QName("http://apache.org/hello_world/types","sayHi"),part.getElementName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBuildImportedWSDLSpacesInPath() throws Exception {
WSDLDefinitionBuilder builder=new WSDLDefinitionBuilder(BusFactory.getDefaultBus());
String wsdlUrl=getClass().getResource("/folder with spaces/import_test.wsdl").toString();
Definition def=builder.build(wsdlUrl);
assertNotNull(def);
Map,?> services=def.getServices();
assertNotNull(services);
assertEquals(1,services.size());
String serviceQName="urn:S1importS2S3/resources/wsdl/S1importsS2S3Test1";
Service service=(Service)services.get(new QName(serviceQName,"S1importsS2S3TestService"));
assertNotNull(service);
Map,?> ports=service.getPorts();
assertNotNull(ports);
assertEquals(1,ports.size());
Port port=service.getPort("S1importsS2S3TestPort");
assertNotNull(port);
}
Class: org.apache.cxf.tools.wsdlto.frontend.jaxws.CatalogTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCatalog() throws Exception {
OASISCatalogManager catalogManager=new OASISCatalogManager();
URL jaxwscatalog=getClass().getResource("/META-INF/jax-ws-catalog.xml");
assertNotNull(jaxwscatalog);
catalogManager.loadCatalog(jaxwscatalog);
String xsd="http://www.w3.org/2005/08/addressing/ws-addr.xsd";
String resolvedSchemaLocation=catalogManager.resolveSystem(xsd);
assertEquals("classpath:/schemas/wsdl/ws-addr.xsd",resolvedSchemaLocation);
ExtendedURIResolver resolver=new ExtendedURIResolver();
InputSource in=resolver.resolve(resolvedSchemaLocation,null);
assertTrue(in.getSystemId(),in.getSystemId().indexOf("core") != -1);
assertTrue(in.getSystemId(),in.getSystemId().indexOf("/schemas/wsdl/ws-addr.xsd") != -1);
}
Class: org.apache.cxf.tools.wsdlto.frontend.jaxws.JAXWSProfileTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testLoadPlugins(){
PluginLoader loader=PluginLoader.getInstance();
assertNotNull(loader);
loader.loadPlugin("/org/apache/cxf/tools/wsdlto/frontend/jaxws/jaxws-plugin.xml");
assertEquals(3,loader.getPlugins().size());
Plugin plugin=null;
for ( Plugin p : loader.getPlugins().values()) {
if (p.getName().contains("jaxws")) {
plugin=p;
}
}
assertNotNull(plugin);
assertEquals("tools-jaxws-frontend",plugin.getName());
assertEquals("2.0",plugin.getVersion());
assertEquals("apache cxf",plugin.getProvider());
Map frontends=loader.getFrontEnds();
assertNotNull(frontends);
assertEquals(3,frontends.size());
FrontEnd frontend=getFrontEnd(frontends,0);
assertEquals("jaxws",frontend.getName());
assertEquals("org.apache.cxf.tools.wsdlto.frontend.jaxws",frontend.getPackage());
assertEquals("JAXWSProfile",frontend.getProfile());
assertNotNull(frontend.getGenerators());
assertNotNull(frontend.getGenerators().getGenerator());
assertEquals(2,frontend.getGenerators().getGenerator().size());
assertEquals("AntGenerator",getGenerator(frontend,0).getName());
assertEquals("ImplGenerator",getGenerator(frontend,1).getName());
FrontEndProfile profile=loader.getFrontEndProfile("jaxws");
assertNotNull(profile);
List generators=profile.getGenerators();
assertNotNull(generators);
assertEquals(2,generators.size());
assertTrue(generators.get(0) instanceof AntGenerator);
assertTrue(generators.get(1) instanceof ImplGenerator);
Processor processor=profile.getProcessor();
assertNotNull(processor);
assertTrue(processor instanceof WSDLToJavaProcessor);
AbstractWSDLBuilder builder=profile.getWSDLBuilder();
assertNotNull(builder);
assertTrue(builder instanceof JAXWSDefinitionBuilder);
Class> container=profile.getContainerClass();
assertEquals(container,JAXWSContainer.class);
assertEquals("/org/apache/cxf/tools/wsdlto/frontend/jaxws/jaxws-toolspec.xml",profile.getToolspec());
}
Class: org.apache.cxf.tools.wsdlto.frontend.jaxws.customization.CustomizationParserTest APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testCopyAllJaxbDeclarations() throws Exception {
Element schema=getDocumentElement("resources/test.xsd");
Element binding=getDocumentElement("resources/embeded_jaxb.xjb");
String checkingPoint="//xsd:annotation/xsd:appinfo/jaxb:schemaBindings/jaxb:package[@name]";
assertNull(selector.queryNode(schema,checkingPoint));
Node jaxwsBindingNode=selector.queryNode(binding,"//jaxws:bindings[@node]");
Node schemaNode=selector.queryNode(schema,"//xsd:schema");
parser.copyAllJaxbDeclarations(schemaNode,(Element)jaxwsBindingNode);
File file=new File(output,"custom_test.xsd");
StaxUtils.writeTo(schemaNode,new FileOutputStream(file));
Document testNode=StaxUtils.read(file);
Node result=selector.queryNode(testNode,checkingPoint);
assertNotNull(result);
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testHasJaxbBindingDeclaration() throws Exception {
Element doc=getDocumentElement("resources/embeded_jaxb.xjb");
Node jaxwsBindingNode=selector.queryNode(doc,"//jaxws:bindings[@node]");
assertNotNull(jaxwsBindingNode);
assertTrue(parser.hasJaxbBindingDeclaration(jaxwsBindingNode));
doc=getDocumentElement("resources/external_jaxws.xml");
jaxwsBindingNode=selector.queryNode(doc,"//jaxws:bindings[@node]");
assertNotNull(jaxwsBindingNode);
assertFalse(parser.hasJaxbBindingDeclaration(jaxwsBindingNode));
}
Class: org.apache.cxf.tools.wsdlto.frontend.jaxws.processor.internal.ParameterProcessorTest InternalCallVerifier EqualityVerifier
@Test public void testAddParameter() throws Exception {
ParameterProcessor processor=new ParameterProcessor(new ToolContext());
JavaMethod method=new JavaMethod();
JavaParameter p1=new JavaParameter("request",String.class.getName(),null);
p1.setStyle(JavaType.Style.IN);
processor.addParameter(null,method,p1);
JavaParameter p2=new JavaParameter("request",String.class.getName(),null);
p2.setStyle(JavaType.Style.OUT);
processor.addParameter(null,method,p2);
assertEquals(1,method.getParameters().size());
assertEquals(JavaType.Style.INOUT,method.getParameters().get(0).getStyle());
}
Class: org.apache.cxf.tools.wsdlto.frontend.jaxws.processor.internal.annotator.WebMethodAnnotatorTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testAddWebMethodAnnotation() throws Exception {
JavaMethod method=new JavaMethod();
method.setName("echoFoo");
method.setOperationName("echoFoo");
method.annotate(new WebMethodAnnotator());
Map annotations=method.getAnnotationMap();
assertNotNull(annotations);
assertEquals(1,annotations.size());
assertEquals("WebMethod",annotations.keySet().iterator().next());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testAddWebResultAnnotation() throws Exception {
JavaMethod method=new JavaMethod();
method.annotate(new WebResultAnnotator());
Map annotations=method.getAnnotationMap();
assertNotNull(annotations);
assertEquals(1,annotations.size());
assertEquals("WebResult",annotations.keySet().iterator().next());
JAnnotation resultAnnotation=annotations.get("WebResult");
assertEquals("@WebResult(name = \"return\")",resultAnnotation.toString());
List elements=resultAnnotation.getElements();
assertNotNull(elements);
assertEquals(1,elements.size());
assertEquals("name",elements.get(0).getName());
assertEquals("return",elements.get(0).getValue());
}
Class: org.apache.cxf.tools.wsdlto.frontend.jaxws.processor.internal.annotator.WebParamAnnotatorTest InternalCallVerifier EqualityVerifier
@Test public void testAnnotateRPC() throws Exception {
init(method,parameter,SOAPBinding.Style.RPC,true);
parameter.annotate(new WebParamAnnotator());
JAnnotation annotation=parameter.getAnnotation("WebParam");
assertEquals(2,annotation.getElements().size());
assertEquals("@WebParam(partName = \"y\", name = \"y\")",annotation.toString());
}
InternalCallVerifier EqualityVerifier
@Test public void testAnnotateDOCBare() throws Exception {
init(method,parameter,SOAPBinding.Style.DOCUMENT,false);
parameter.annotate(new WebParamAnnotator());
JAnnotation annotation=parameter.getAnnotation("WebParam");
assertEquals("@WebParam(partName = \"y\", name = \"x\", " + "targetNamespace = \"http://apache.org/cxf\")",annotation.toString());
List elements=annotation.getElements();
assertEquals(3,elements.size());
}
InternalCallVerifier EqualityVerifier
@Test public void testAnnotateDOCWrapped() throws Exception {
init(method,parameter,SOAPBinding.Style.DOCUMENT,true);
parameter.annotate(new WebParamAnnotator());
JAnnotation annotation=parameter.getAnnotation("WebParam");
assertEquals("@WebParam(name = \"x\", targetNamespace = \"http://apache.org/cxf\")",annotation.toString());
List elements=annotation.getElements();
assertEquals(2,elements.size());
assertEquals("http://apache.org/cxf",elements.get(1).getValue());
assertEquals("x",elements.get(0).getValue());
}
Class: org.apache.cxf.tools.wsdlto.frontend.jaxws.processor.internal.annotator.XmlSeeAlsoAnnotatorTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testAddXmlSeeAlsoAnnotation() throws Exception {
JavaInterface intf=new JavaInterface();
assertFalse(intf.getImports().hasNext());
ClassCollector collector=new ClassCollector();
collector.getTypesPackages().add(ObjectFactory.class.getPackage().getName());
intf.annotate(new XmlSeeAlsoAnnotator(collector));
Iterator iter=intf.getImports();
assertEquals("javax.xml.bind.annotation.XmlSeeAlso",iter.next());
assertEquals("@XmlSeeAlso({" + ObjectFactory.class.getName() + ".class})",intf.getAnnotations().iterator().next().toString());
}
Class: org.apache.cxf.tools.wsdlto.frontend.jaxws.processor.internal.mapper.InterfaceMapperTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testMap() throws Exception {
InterfaceInfo interfaceInfo=new InterfaceInfo(new ServiceInfo(),new QName("http://apache.org/hello_world_soap_http","interfaceTest"));
ToolContext context=new ToolContext();
context.put(ToolConstants.CFG_WSDLURL,"http://localhost/?wsdl");
JavaInterface intf=new InterfaceMapper(context).map(interfaceInfo);
assertNotNull(intf);
assertEquals("interfaceTest",intf.getWebServiceName());
assertEquals("InterfaceTest",intf.getName());
assertEquals("http://apache.org/hello_world_soap_http",intf.getNamespace());
assertEquals("org.apache.hello_world_soap_http",intf.getPackageName());
assertEquals("http://localhost/?wsdl",intf.getLocation());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testMapWithUniqueWsdlLoc() throws Exception {
InterfaceInfo interfaceInfo=new InterfaceInfo(new ServiceInfo(),new QName("http://apache.org/hello_world_soap_http","interfaceTest"));
ToolContext context=new ToolContext();
context.put(ToolConstants.CFG_WSDLURL,"http://localhost/?wsdl");
context.put(ToolConstants.CFG_WSDLLOCATION,"/foo/blah.wsdl");
JavaInterface intf=new InterfaceMapper(context).map(interfaceInfo);
assertNotNull(intf);
assertEquals("interfaceTest",intf.getWebServiceName());
assertEquals("InterfaceTest",intf.getName());
assertEquals("http://apache.org/hello_world_soap_http",intf.getNamespace());
assertEquals("org.apache.hello_world_soap_http",intf.getPackageName());
assertEquals("/foo/blah.wsdl",intf.getLocation());
}
Class: org.apache.cxf.tools.wsdlto.frontend.jaxws.processor.internal.mapper.MethodMapperTest BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testMapWrappedOperation() throws Exception {
OperationInfo operation=getOperation();
operation.setUnwrappedOperation(operation);
JavaMethod method=new MethodMapper().map(operation);
assertNotNull(method);
assertTrue(method.isWrapperStyle());
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testMapOneWayOperation() throws Exception {
OperationInfo operation=getOperation();
MessageInfo inputMessage=operation.createMessage(new QName("urn:test:ns","testInputMessage"),MessageInfo.Type.INPUT);
operation.setInput("input",inputMessage);
JavaMethod method=new MethodMapper().map(operation);
assertNotNull(method);
assertTrue(method.isOneWay());
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testMap() throws Exception {
JavaMethod method=new MethodMapper().map(getOperation());
assertNotNull(method);
assertEquals(javax.jws.soap.SOAPBinding.Style.DOCUMENT,method.getSoapStyle());
assertEquals("operationTest",method.getName());
assertEquals("OperationTest",method.getOperationName());
assertEquals(OperationType.REQUEST_RESPONSE,method.getStyle());
assertFalse(method.isWrapperStyle());
assertFalse(method.isOneWay());
}
Class: org.apache.cxf.tools.wsdlto.frontend.jaxws.wsdl11.JAXWSDefinitionBuilderTest APIUtilityVerifier IterativeVerifier InternalCallVerifier EqualityVerifier
@Test public void testCustomization(){
env.put(ToolConstants.CFG_WSDLURL,getClass().getResource("resources/hello_world.wsdl").toString());
env.put(ToolConstants.CFG_BINDING,getClass().getResource("resources/binding2.xml").toString());
JAXWSDefinitionBuilder builder=new JAXWSDefinitionBuilder();
builder.setContext(env);
builder.setBus(BusFactory.getDefaultBus());
builder.build();
builder.customize();
Definition customizedDef=builder.getWSDLModel();
List> defExtensionList=customizedDef.getExtensibilityElements();
Iterator> ite=defExtensionList.iterator();
while (ite.hasNext()) {
ExtensibilityElement extElement=(ExtensibilityElement)ite.next();
JAXWSBinding binding=(JAXWSBinding)extElement;
assertEquals("Customized package name does not been parsered","com.foo",binding.getPackage());
assertEquals("Customized enableAsync does not parsered",true,binding.isEnableAsyncMapping());
}
PortType portType=customizedDef.getPortType(new QName("http://apache.org/hello_world_soap_http","Greeter"));
List> portTypeList=portType.getExtensibilityElements();
JAXWSBinding binding=(JAXWSBinding)portTypeList.get(0);
assertEquals("Customized enable EnableWrapperStyle name does not been parsered",true,binding.isEnableWrapperStyle());
List> opList=portType.getOperations();
Operation operation=(Operation)opList.get(0);
List> extList=operation.getExtensibilityElements();
binding=(JAXWSBinding)extList.get(0);
assertEquals("Customized method name does not parsered","echoMeOneWay",binding.getMethodName());
assertEquals("Customized parameter element name does not parsered","number1",binding.getJaxwsParas().get(0).getElementName().getLocalPart());
assertEquals("Customized parameter message name does not parsered","greetMeOneWayRequest",binding.getJaxwsParas().get(0).getMessageName());
assertEquals("customized parameter name does not parsered","num1",binding.getJaxwsParas().get(0).getName());
}
BooleanVerifier InternalCallVerifier
@Test public void testNoService(){
env.put(ToolConstants.CFG_WSDLURL,getClass().getResource("resources/build.wsdl").toString());
JAXWSDefinitionBuilder builder=new JAXWSDefinitionBuilder();
builder.setContext(env);
builder.setBus(BusFactory.getDefaultBus());
builder.build();
Definition def=builder.getWSDLModel();
assertTrue(def.getServices().keySet().contains(new QName("http://apache.org/hello_world_soap_http","SOAPService")));
}
APIUtilityVerifier IterativeVerifier InternalCallVerifier EqualityVerifier
@Test public void testCustomizationWithDifferentNS(){
env.put(ToolConstants.CFG_WSDLURL,getClass().getResource("resources/hello_world.wsdl").toString());
env.put(ToolConstants.CFG_BINDING,getClass().getResource("resources/binding3.xml").toString());
JAXWSDefinitionBuilder builder=new JAXWSDefinitionBuilder();
builder.setContext(env);
builder.setBus(BusFactory.getDefaultBus());
builder.build();
builder.customize();
Definition customizedDef=builder.getWSDLModel();
List> defExtensionList=customizedDef.getExtensibilityElements();
Iterator> ite=defExtensionList.iterator();
while (ite.hasNext()) {
ExtensibilityElement extElement=(ExtensibilityElement)ite.next();
JAXWSBinding binding=(JAXWSBinding)extElement;
assertEquals("Customized package name does not been parsered","com.foo",binding.getPackage());
assertEquals("Customized enableAsync does not parsered",true,binding.isEnableAsyncMapping());
}
PortType portType=customizedDef.getPortType(new QName("http://apache.org/hello_world_soap_http","Greeter"));
List> portTypeList=portType.getExtensibilityElements();
JAXWSBinding binding=(JAXWSBinding)portTypeList.get(0);
assertEquals("Customized enable EnableWrapperStyle name does not been parsered",true,binding.isEnableWrapperStyle());
List> opList=portType.getOperations();
Operation operation=(Operation)opList.get(0);
List> extList=operation.getExtensibilityElements();
binding=(JAXWSBinding)extList.get(0);
assertEquals("Customized method name does not parsered","echoMeOneWay",binding.getMethodName());
assertEquals("Customized parameter element name does not parsered","number1",binding.getJaxwsParas().get(0).getElementName().getLocalPart());
assertEquals("Customized parameter message name does not parsered","greetMeOneWayRequest",binding.getJaxwsParas().get(0).getMessageName());
assertEquals("customized parameter name does not parsered","num1",binding.getJaxwsParas().get(0).getName());
}
Class: org.apache.cxf.tools.wsdlto.jaxws.CodeGenBugTest APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testNonUniqueBody() throws Exception {
try {
env.put(ToolConstants.CFG_WSDLURL,getLocation("/wsdl2java_wsdl/cxf939/bug.wsdl"));
env.remove(ToolConstants.CFG_VALIDATE_WSDL);
processor.setContext(env);
processor.execute();
}
catch ( Exception e) {
String ns="http://bugs.cxf/services/bug1";
QName bug1=new QName(ns,"myBug1");
QName bug2=new QName(ns,"myBug2");
Message msg1=new Message("NON_UNIQUE_BODY",UniqueBodyValidator.LOG,bug1,bug1,bug2,bug1);
Message msg2=new Message("NON_UNIQUE_BODY",UniqueBodyValidator.LOG,bug1,bug2,bug1,bug1);
boolean boolA=msg1.toString().trim().equals(e.getMessage().trim());
boolean boolB=msg2.toString().trim().equals(e.getMessage().trim());
assertTrue(boolA || boolB);
}
}
Class: org.apache.cxf.tools.wsdlto.jaxws.CodeGenTest UtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testInvalidXjcArgDummyPluginUsage() throws Exception {
env.put(ToolConstants.CFG_WSDLURL,getLocation("/wsdl2java_wsdl/hello_world.wsdl"));
env.put(ToolConstants.CFG_XJC_ARGS,"-" + DummyXjcPlugin.XDUMMY_XJC_PLUGIN + ",-"+ DummyXjcPlugin.XDUMMY_XJC_PLUGIN+ ":some_rubbish_argument");
processor.setContext(env);
String msg=null;
try {
processor.execute();
fail("Expect a ToolException on invalid xjc argument");
}
catch ( ToolException expected) {
msg=expected.getMessage();
}
assertNotNull(msg);
assertTrue(":some_rubbish_argument is present in :" + msg,msg.indexOf(":some_rubbish_argument") != -1);
assertTrue("Dummy plugin usage string present in :" + msg,msg.indexOf(DummyXjcPlugin.DUMMY_ARG) != -1);
}
UtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testXjcMinusXArgGivesPluginUsage() throws Exception {
env.put(ToolConstants.CFG_WSDLURL,getLocation("/wsdl2java_wsdl/hello_world.wsdl"));
env.put(ToolConstants.CFG_XJC_ARGS,"-X");
processor.setContext(env);
String msg=null;
try {
processor.execute();
fail("Expect a ToolException on invalid xjc argument");
}
catch ( ToolException expected) {
msg=expected.getMessage();
}
assertNotNull(msg);
assertTrue("Dummy plugin usage string present in :" + msg,msg.indexOf(DummyXjcPlugin.DUMMY_ARG) != -1);
assertTrue("No BadParameter in msg:" + msg,msg.indexOf("Bad") == -1);
}
Class: org.apache.cxf.tools.wsdlto.jaxws.JAXWSContainerTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCodeGen(){
try {
JAXWSContainer container=new JAXWSContainer(null);
ToolContext context=new ToolContext();
context.put(ToolConstants.CFG_OUTPUTDIR,output.getCanonicalPath());
context.put(ToolConstants.CFG_WSDLURL,getLocation("/wsdl2java_wsdl/hello_world.wsdl"));
context.put(DataBindingProfile.class,PluginLoader.getInstance().getDataBindingProfile("jaxb"));
context.put(FrontEndProfile.class,PluginLoader.getInstance().getFrontEndProfile("jaxws"));
List generatorNames=Arrays.asList(new String[]{ToolConstants.CLT_GENERATOR,ToolConstants.SVR_GENERATOR,ToolConstants.IMPL_GENERATOR,ToolConstants.ANT_GENERATOR,ToolConstants.SERVICE_GENERATOR,ToolConstants.FAULT_GENERATOR,ToolConstants.SEI_GENERATOR});
FrontEndProfile frontend=context.get(FrontEndProfile.class);
List generators=frontend.getGenerators();
for ( FrontEndGenerator generator : generators) {
assertTrue(generatorNames.contains(generator.getName()));
}
container.setContext(context);
container.execute();
assertNotNull(output.list());
assertEquals(1,output.list().length);
assertTrue(new File(output,"org/apache/cxf/w2j/hello_world_soap_http/Greeter.java").exists());
assertTrue(new File(output,"org/apache/cxf/w2j/hello_world_soap_http/SOAPService.java").exists());
assertTrue(new File(output,"org/apache/cxf/w2j/hello_world_soap_http/NoSuchCodeLitFault.java").exists());
assertTrue(new File(output,"org/apache/cxf/w2j/hello_world_soap_http/types/SayHi.java").exists());
assertTrue(new File(output,"org/apache/cxf/w2j/hello_world_soap_http/types/GreetMe.java").exists());
JavaModel javaModel=context.get(JavaModel.class);
Map interfaces=javaModel.getInterfaces();
assertEquals(1,interfaces.size());
JavaInterface intf=interfaces.values().iterator().next();
assertEquals("http://cxf.apache.org/w2j/hello_world_soap_http",intf.getNamespace());
assertEquals("Greeter",intf.getName());
assertEquals("org.apache.cxf.w2j.hello_world_soap_http",intf.getPackageName());
List methods=intf.getMethods();
assertEquals(6,methods.size());
Boolean methodSame=false;
for ( JavaMethod m1 : methods) {
if (m1.getName().equals("testDocLitFault")) {
methodSame=true;
break;
}
}
assertTrue(methodSame);
}
catch ( Exception e) {
e.printStackTrace();
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSuppressCodeGen(){
try {
JAXWSContainer container=new JAXWSContainer(null);
ToolContext context=new ToolContext();
context.put(ToolConstants.CFG_SUPPRESS_GEN,"suppress");
context.put(ToolConstants.CFG_OUTPUTDIR,output.getCanonicalPath());
context.put(ToolConstants.CFG_WSDLURL,getLocation("/wsdl2java_wsdl/hello_world.wsdl"));
context.put(DataBindingProfile.class,PluginLoader.getInstance().getDataBindingProfile("jaxb"));
context.put(FrontEndProfile.class,PluginLoader.getInstance().getFrontEndProfile("jaxws"));
container.setContext(context);
container.execute();
assertNotNull(output.list());
assertEquals(0,output.list().length);
Map map=CastUtils.cast((Map,?>)context.get(WSDLToJavaProcessor.MODEL_MAP));
JavaModel javaModel=map.get(new QName("http://cxf.apache.org/w2j/hello_world_soap_http","SOAPService"));
assertNotNull(javaModel);
Map interfaces=javaModel.getInterfaces();
assertEquals(1,interfaces.size());
JavaInterface intf=interfaces.values().iterator().next();
String interfaceName=intf.getName();
assertEquals("Greeter",interfaceName);
assertEquals("http://cxf.apache.org/w2j/hello_world_soap_http",intf.getNamespace());
assertEquals("org.apache.cxf.w2j.hello_world_soap_http",intf.getPackageName());
List methods=intf.getMethods();
assertEquals(6,methods.size());
Boolean methodSame=false;
JavaMethod m1=null;
for ( JavaMethod m2 : methods) {
if (m2.getName().equals("testDocLitFault")) {
methodSame=true;
m1=m2;
break;
}
}
assertTrue(methodSame);
assertEquals(2,m1.getExceptions().size());
List names=new ArrayList();
for ( JavaException exc : m1.getExceptions()) {
names.add(exc.getName());
}
assertTrue("BadRecordLitFault",names.contains("BadRecordLitFault"));
assertTrue("NoSuchCodeLitFault",names.contains("NoSuchCodeLitFault"));
String address=null;
for ( JavaServiceClass service : javaModel.getServiceClasses().values()) {
if ("SOAPService_Test1".equals(service.getName())) {
continue;
}
List ports=service.getPorts();
for ( JavaPort port : ports) {
if (interfaceName.equals(port.getPortType())) {
address=port.getBindingAdress();
break;
}
}
if (!"".equals(address)) {
break;
}
}
assertEquals("http://localhost:9000/SoapContext/SoapPort",address);
}
catch ( Exception e) {
e.printStackTrace();
}
}
Class: org.apache.cxf.tools.wsdlto.jaxws.wsdl11.JAXWSDefinitionBuilderTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBuildDefinitionWithXMLBinding(){
String qname="http://apache.org/hello_world_xml_http/bare";
String wsdlUrl=getClass().getResource("resources/hello_world_xml_bare.wsdl").toString();
JAXWSDefinitionBuilder builder=new JAXWSDefinitionBuilder();
builder.setBus(BusFactory.getDefaultBus());
builder.setContext(env);
Definition def=builder.build(wsdlUrl);
assertNotNull(def);
Map,?> services=def.getServices();
assertNotNull(services);
assertEquals(1,services.size());
Service service=(Service)services.get(new QName(qname,"XMLService"));
assertNotNull(service);
Map,?> ports=service.getPorts();
assertNotNull(ports);
assertEquals(1,ports.size());
Port port=service.getPort("XMLPort");
assertNotNull(port);
assertEquals(1,port.getExtensibilityElements().size());
Object obj=port.getExtensibilityElements().get(0);
if (obj instanceof JAXBExtensibilityElement) {
obj=((JAXBExtensibilityElement)obj).getValue();
}
assertTrue(obj.getClass().getName() + " is not an AddressType",obj instanceof AddressType);
Binding binding=port.getBinding();
assertNotNull(binding);
assertEquals(new QName(qname,"Greeter_XMLBinding"),binding.getQName());
BindingOperation operation=binding.getBindingOperation("sayHi",null,null);
assertNotNull(operation);
BindingInput input=operation.getBindingInput();
assertNotNull(input);
assertEquals(1,input.getExtensibilityElements().size());
obj=input.getExtensibilityElements().get(0);
if (obj instanceof JAXBExtensibilityElement) {
obj=((JAXBExtensibilityElement)obj).getValue();
}
assertTrue(obj.getClass().getName() + " is not an XMLBindingMessageFormat",obj instanceof XMLBindingMessageFormat);
}
Class: org.apache.cxf.transport.http.DestinationRegistryImplTest IterativeVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testAddAndGetDestinations() throws Exception {
setUpDestinations();
Set paths=registry.getDestinationsPaths();
assertEquals(REGISTERED_PATHS.length,paths.size());
for (int i=0; i < REGISTERED_PATHS.length; i++) {
assertTrue(paths.contains(REGISTERED_PATHS[i]));
AbstractHTTPDestination path=registry.getDestinationForPath(REGISTERED_PATHS[i]);
assertNotNull(path);
}
}
IterativeVerifier BranchVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCheckRestfulRequest() throws Exception {
setUpDestinations();
for (int i=0; i < REQUEST_PATHS.length; i++) {
final int mi=MATCHED_PATH_INDEXES[i];
for (int j=0; j < REGISTERED_PATHS.length; j++) {
AbstractHTTPDestination target=registry.getDestinationForPath(REGISTERED_PATHS[j]);
if (mi == j) {
EasyMock.expect(target.getMessageObserver()).andReturn(observer);
EndpointInfo endpoint=new EndpointInfo();
endpoint.setAddress(REGISTERED_PATHS[mi]);
endpoint.setName(QNAME);
EasyMock.expect(target.getEndpointInfo()).andReturn(endpoint);
}
else {
EasyMock.expect(target.getMessageObserver()).andReturn(observer).anyTimes();
}
}
control.replay();
AbstractHTTPDestination destination=registry.checkRestfulRequest(REQUEST_PATHS[i]);
if (0 <= mi) {
EndpointInfo endpoint=destination.getEndpointInfo();
assertNotNull(endpoint);
assertEquals(endpoint.getAddress(),REGISTERED_PATHS[mi]);
}
else {
assertNull(destination);
}
control.verify();
control.reset();
}
}
Class: org.apache.cxf.transport.http.HTTPConduitTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testAuthPolicyFromEndpointInfo() throws Exception {
Bus bus=new ExtensionManagerBus();
EndpointInfo ei=new EndpointInfo();
AuthorizationPolicy ap=new AuthorizationPolicy();
ap.setPassword("password");
ap.setUserName("testUser");
ei.addExtensor(ap);
ei.setAddress("http://nowhere.com/bar/foo");
HTTPConduit conduit=new URLConnectionHTTPConduit(bus,ei,null);
conduit.finalizeConfig();
Message message=getNewMessage();
conduit.prepare(message);
Map> headers=CastUtils.cast((Map,?>)message.get(Message.PROTOCOL_HEADERS));
assertNotNull("Authorization Header should exist",headers.get("Authorization"));
assertEquals("Unexpected Authorization Token","Basic " + Base64Utility.encode("testUser:password".getBytes()),headers.get("Authorization").get(0));
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
/**
* This test verfies that the "getTarget() call returns the correct
* EndpointReferenceType for the given endpoint address.
*/
@Test public void testGetTarget() throws Exception {
Bus bus=new ExtensionManagerBus();
EndpointInfo ei=new EndpointInfo();
ei.setAddress("http://nowhere.com/bar/foo");
HTTPConduit conduit=new URLConnectionHTTPConduit(bus,ei,null);
conduit.finalizeConfig();
EndpointReferenceType target=EndpointReferenceUtils.getEndpointReference("http://nowhere.com/bar/foo");
EndpointReferenceType ref=conduit.getTarget();
assertNotNull("unexpected null target",ref);
assertEquals("unexpected target",EndpointReferenceUtils.getAddress(ref),EndpointReferenceUtils.getAddress(target));
assertEquals("unexpected address",conduit.getAddress(),"http://nowhere.com/bar/foo");
assertEquals("unexpected on-demand URL",conduit.getURI().getPath(),"/bar/foo");
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
/**
* This test verifies the precedence of Authorization Information.
* Setting authorization information on the Message takes precedence
* over a Basic Auth Supplier with preemptive UserPass, and that
* followed by setting it directly on the Conduit.
*/
@Test public void testAuthPolicyPrecedence() throws Exception {
Bus bus=new ExtensionManagerBus();
EndpointInfo ei=new EndpointInfo();
ei.setAddress("http://nowhere.com/bar/foo");
HTTPConduit conduit=new URLConnectionHTTPConduit(bus,ei,null);
conduit.finalizeConfig();
conduit.getAuthorization().setUserName("Satan");
conduit.getAuthorization().setPassword("hell");
Message message=getNewMessage();
conduit.prepare(message);
Map> headers=CastUtils.cast((Map,?>)message.get(Message.PROTOCOL_HEADERS));
assertNotNull("Authorization Header should exist",headers.get("Authorization"));
assertEquals("Unexpected Authorization Token","Basic " + Base64Utility.encode("Satan:hell".getBytes()),headers.get("Authorization").get(0));
conduit.setAuthSupplier(new TestAuthSupplier());
message=getNewMessage();
conduit.prepare(message);
headers=CastUtils.cast((Map,?>)message.get(Message.PROTOCOL_HEADERS));
List authorization=headers.get("Authorization");
assertNotNull("Authorization Token must be set",authorization);
assertEquals("Wrong Authorization Token","myauth",authorization.get(0));
conduit.setAuthSupplier(null);
AuthorizationPolicy authPolicy=new AuthorizationPolicy();
authPolicy.setUserName("Hello");
authPolicy.setPassword("world");
authPolicy.setAuthorizationType("Basic");
message=getNewMessage();
message.put(AuthorizationPolicy.class,authPolicy);
conduit.prepare(message);
headers=CastUtils.cast((Map,?>)message.get(Message.PROTOCOL_HEADERS));
assertEquals("Unexpected Authorization Token","Basic " + Base64Utility.encode("Hello:world".getBytes()),headers.get("Authorization").get(0));
}
Class: org.apache.cxf.transport.http.HTTPConduitURLConnectionTest InternalCallVerifier EqualityVerifier
/**
* This test verifies that URL used is overridden by having the
* ENDPOINT_ADDRESS set on the Message.
*/
@Test public void testConnectionURLOverride() throws Exception {
Bus bus=new ExtensionManagerBus();
EndpointInfo ei=new EndpointInfo();
ei.setAddress("http://nowhere.null/bar/foo");
HTTPConduit conduit=new URLConnectionHTTPConduit(bus,ei,null);
conduit.finalizeConfig();
Message message=getNewMessage();
message.put(Message.ENDPOINT_ADDRESS,"http://somewhere.different/");
conduit.prepare(message);
HttpURLConnection con=(HttpURLConnection)message.get("http.connection");
assertEquals("Unexpected URL address",con.getURL().toString(),"http://somewhere.different/");
}
InternalCallVerifier EqualityVerifier
/**
* This test verifies that the "prepare" call places an HttpURLConnection on
* the Message and that its URL matches the endpoint.
*/
@Test public void testConnectionURL() throws Exception {
Bus bus=new ExtensionManagerBus();
EndpointInfo ei=new EndpointInfo();
ei.setAddress("http://nowhere.com/bar/foo");
HTTPConduit conduit=new URLConnectionHTTPConduit(bus,ei,null);
conduit.finalizeConfig();
Message message=getNewMessage();
conduit.prepare(message);
HttpURLConnection con=(HttpURLConnection)message.get("http.connection");
assertEquals("Unexpected URL address",con.getURL().toString(),ei.getAddress());
}
Class: org.apache.cxf.transport.http.HeadersTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void setHeadersTest() throws Exception {
String[] headerNames={"Content-Type","authorization","soapAction"};
String[] headerValues={"text/xml","Basic Zm9vOmJhcg==","foo"};
Map> inmap=new HashMap>();
for (int i=0; i < headerNames.length; i++) {
inmap.put(headerNames[i],Arrays.asList(headerValues[i]));
}
HttpServletRequest req=control.createMock(HttpServletRequest.class);
EasyMock.expect(req.getHeaderNames()).andReturn(Collections.enumeration(inmap.keySet()));
for (int i=0; i < headerNames.length; i++) {
EasyMock.expect(req.getHeaders(headerNames[i])).andReturn(Collections.enumeration(inmap.get(headerNames[i])));
}
EasyMock.expect(req.getContentType()).andReturn(headerValues[0]).anyTimes();
control.replay();
Message message=new MessageImpl();
message.put(AbstractHTTPDestination.HTTP_REQUEST,req);
Headers headers=new Headers(message);
headers.copyFromRequest(req);
Map> protocolHeaders=CastUtils.cast((Map,?>)message.get(Message.PROTOCOL_HEADERS));
assertTrue("unexpected size",protocolHeaders.size() == headerNames.length);
assertEquals("unexpected header",protocolHeaders.get("Content-Type").get(0),headerValues[0]);
assertEquals("unexpected header",protocolHeaders.get("content-type").get(0),headerValues[0]);
assertEquals("unexpected header",protocolHeaders.get("CONTENT-TYPE").get(0),headerValues[0]);
assertEquals("unexpected header",protocolHeaders.get("content-TYPE").get(0),headerValues[0]);
assertEquals("unexpected header",protocolHeaders.get("Authorization").get(0),headerValues[1]);
assertEquals("unexpected header",protocolHeaders.get("authorization").get(0),headerValues[1]);
assertEquals("unexpected header",protocolHeaders.get("AUTHORIZATION").get(0),headerValues[1]);
assertEquals("unexpected header",protocolHeaders.get("authoriZATION").get(0),headerValues[1]);
assertEquals("unexpected header",protocolHeaders.get("SOAPAction").get(0),headerValues[2]);
assertEquals("unexpected header",protocolHeaders.get("soapaction").get(0),headerValues[2]);
assertEquals("unexpected header",protocolHeaders.get("SOAPACTION").get(0),headerValues[2]);
assertEquals("unexpected header",protocolHeaders.get("soapAction").get(0),headerValues[2]);
}
Class: org.apache.cxf.transport.http.asyncclient.AsyncHTTPConduitTest InternalCallVerifier EqualityVerifier
@Test public void testInvocationWithTransportId() throws Exception {
String address="http://localhost:" + PORT + "/SoapContext/SoapPort";
JaxWsProxyFactoryBean factory=new JaxWsProxyFactoryBean();
factory.setServiceClass(Greeter.class);
factory.setAddress(address);
factory.setTransportId("http://cxf.apache.org/transports/http/http-client");
Greeter greeter=factory.create(Greeter.class);
String response=greeter.greetMe("test");
assertEquals("Get a wrong response","Hello test",response);
}
IterativeVerifier InternalCallVerifier EqualityVerifier IgnoredMethod HybridVerifier
@Test @Ignore("peformance test") public void testCalls() throws Exception {
updateAddressPort(g,PORT);
for (int x=0; x < 10000; x++) {
String value=g.greetMe(request);
assertEquals("Hello " + request,value);
}
long start=System.currentTimeMillis();
for (int x=0; x < 10000; x++) {
g.greetMe(request);
}
long end=System.currentTimeMillis();
System.out.println("Total: " + (end - start));
}
InternalCallVerifier EqualityVerifier
@Test public void testInovationWithHCAddress() throws Exception {
String address="hc://http://localhost:" + PORT + "/SoapContext/SoapPort";
JaxWsProxyFactoryBean factory=new JaxWsProxyFactoryBean();
factory.setServiceClass(Greeter.class);
factory.setAddress(address);
Greeter greeter=factory.create(Greeter.class);
String response=greeter.greetMe("test");
assertEquals("Get a wrong response","Hello test",response);
}
InternalCallVerifier EqualityVerifier
@Test public void testCall() throws Exception {
updateAddressPort(g,PORT);
assertEquals("Hello " + request,g.greetMe(request));
HTTPConduit c=(HTTPConduit)ClientProxy.getClient(g).getConduit();
HTTPClientPolicy cp=new HTTPClientPolicy();
cp.setAllowChunking(false);
c.setClient(cp);
assertEquals("Hello " + request,g.greetMe(request));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testCallAsync() throws Exception {
updateAddressPort(g,PORT);
GreetMeResponse resp=(GreetMeResponse)g.greetMeAsync(request,new AsyncHandler(){
public void handleResponse( Response res){
try {
res.get().getResponseType();
}
catch ( InterruptedException e) {
e.printStackTrace();
}
catch ( ExecutionException e) {
e.printStackTrace();
}
}
}
).get();
assertEquals("Hello " + request,resp.getResponseType());
g.greetMeLaterAsync(1000,new AsyncHandler(){
public void handleResponse( Response res){
}
}
).get();
}
Class: org.apache.cxf.transport.http.auth.DigestAuthSupplierTest InternalCallVerifier EqualityVerifier
@Test public void testEncode() throws Exception {
String origNonce="MTI0ODg3OTc5NzE2OTplZGUyYTg0Yzk2NTFkY2YyNjc1Y2JjZjU2MTUzZmQyYw==";
String fullHeader="Digest realm=\"MyCompany realm.\", qop=\"auth\"," + "nonce=\"" + origNonce + "\"";
DigestAuthSupplier authSupplier=new DigestAuthSupplier(){
@Override public String createCnonce() throws UnsupportedEncodingException {
return "27db039b76362f3d55da10652baee38c";
}
}
;
IMocksControl control=EasyMock.createControl();
AuthorizationPolicy authorizationPolicy=new AuthorizationPolicy();
authorizationPolicy.setUserName("testUser");
authorizationPolicy.setPassword("testPassword");
URI uri=new URI("http://myserver");
Message message=new MessageImpl();
control.replay();
String authToken=authSupplier.getAuthorization(authorizationPolicy,uri,message,fullHeader);
HttpAuthHeader authHeader=new HttpAuthHeader(authToken);
assertEquals("Digest",authHeader.getAuthType());
Map params=authHeader.getParams();
Map expectedParams=new HashMap();
expectedParams.put("response","28e616b6868f60aaf9b19bb5b172f076");
expectedParams.put("cnonce","27db039b76362f3d55da10652baee38c");
expectedParams.put("username","testUser");
expectedParams.put("nc","00000001");
expectedParams.put("nonce","MTI0ODg3OTc5NzE2OTplZGUyYTg0Yzk2NTFkY2YyNjc1Y2JjZjU2MTUzZmQyYw==");
expectedParams.put("realm","MyCompany realm.");
expectedParams.put("qop","auth");
expectedParams.put("uri","");
expectedParams.put("algorithm","MD5");
assertEquals(expectedParams,params);
control.verify();
}
Class: org.apache.cxf.transport.http.auth.HttpAuthHeaderTest InternalCallVerifier EqualityVerifier
@Test public void testParse(){
HttpAuthHeader authHeader=new HttpAuthHeader("Digest nonce=\"TUzZmQyYw==\", username=\"testUser\"");
assertEquals("Digest",authHeader.getAuthType());
Map params=authHeader.getParams();
Map expectedParams=new HashMap();
expectedParams.put("username","testUser");
expectedParams.put("nonce","TUzZmQyYw==");
assertEquals(expectedParams,params);
}
Class: org.apache.cxf.transport.http.netty.client.NettyHttpConduitFactoryTest BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testLoadingHttpConduitFactory() throws Exception {
bus=BusFactory.getDefaultBus(true);
assertNotNull("Cannot get bus",bus);
HTTPConduitFactory factory=bus.getExtension(HTTPConduitFactory.class);
assertNotNull("Cannot get HTTPConduitFactory",factory);
assertTrue(NettyHttpConduitFactory.class.isInstance(factory));
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testShutdownEventLoopGroup() throws Exception {
bus=BusFactory.getDefaultBus(true);
assertNotNull("Cannot get bus",bus);
NettyHttpTransportFactory factory=bus.getExtension(NettyHttpTransportFactory.class);
assertNotNull("Cannot get NettyHttpTransportFactory",factory);
ServiceInfo serviceInfo=new ServiceInfo();
serviceInfo.setName(new QName("bla","Service"));
EndpointInfo ei=new EndpointInfo(serviceInfo,"");
ei.setName(new QName("bla","Port"));
ei.setAddress("netty://foo");
factory.getConduit(ei,null,bus);
bus.shutdown(true);
EventLoopGroup eventLoopGroup=bus.getExtension(EventLoopGroup.class);
assertNotNull("We should find the EventLoopGroup here.",eventLoopGroup);
assertTrue("The eventLoopGroup should be shutdown.",eventLoopGroup.isShutdown());
}
Class: org.apache.cxf.transport.http.netty.client.integration.NettyClientTest InternalCallVerifier EqualityVerifier
@Test public void testInovationWithNettyAddress() throws Exception {
String address="netty://http://localhost:" + PORT + "/SoapContext/SoapPort";
JaxWsProxyFactoryBean factory=new JaxWsProxyFactoryBean();
factory.setServiceClass(Greeter.class);
factory.setAddress(address);
Greeter greeter=factory.create(Greeter.class);
String response=greeter.greetMe("test");
assertEquals("Get a wrong response","Hello test",response);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testCallAsync() throws Exception {
updateAddressPort(g,PORT);
GreetMeResponse resp=(GreetMeResponse)g.greetMeAsync("asyncTest",new AsyncHandler(){
public void handleResponse( Response res){
try {
res.get().getResponseType();
}
catch ( InterruptedException e) {
e.printStackTrace();
}
catch ( ExecutionException e) {
e.printStackTrace();
}
}
}
).get();
assertEquals("Hello asyncTest",resp.getResponseType());
MyLaterResponseHandler handler=new MyLaterResponseHandler();
g.greetMeLaterAsync(1000,handler).get();
assertEquals("Hello, finally!",handler.getResponse().getResponseType());
}
InternalCallVerifier EqualityVerifier
@Test public void testInvocationWithTransportId() throws Exception {
String address="http://localhost:" + PORT + "/SoapContext/SoapPort";
JaxWsProxyFactoryBean factory=new JaxWsProxyFactoryBean();
factory.setServiceClass(Greeter.class);
factory.setAddress(address);
factory.setTransportId("http://cxf.apache.org/transports/http/netty/client");
Greeter greeter=factory.create(Greeter.class);
String response=greeter.greetMe("test");
assertEquals("Get a wrong response","Hello test",response);
}
InternalCallVerifier EqualityVerifier
@Test public void testInvocation() throws Exception {
updateAddressPort(g,PORT);
String response=g.greetMe("test");
assertEquals("Get a wrong response","Hello test",response);
}
Class: org.apache.cxf.transport.http.netty.client.integration.SSLNettyClientTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testInvocation() throws Exception {
setupTLS(g);
setAddress(g,address);
String response=g.greetMe("test");
assertEquals("Get a wrong response","Hello test",response);
GreetMeResponse resp=(GreetMeResponse)g.greetMeAsync("asyncTest",new AsyncHandler(){
public void handleResponse( Response res){
try {
res.get().getResponseType();
}
catch ( InterruptedException e) {
e.printStackTrace();
}
catch ( ExecutionException e) {
e.printStackTrace();
}
}
}
).get();
assertEquals("Hello asyncTest",resp.getResponseType());
MyLaterResponseHandler handler=new MyLaterResponseHandler();
g.greetMeLaterAsync(1000,handler).get();
assertEquals("Hello, finally!",handler.getResponse().getResponseType());
}
Class: org.apache.cxf.transport.http.netty.server.NettyHttpDestinationTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetAnonBackChannel() throws Exception {
destination=setUpDestination(false,false);
setUpDoService(false);
destination.doService(request,response);
setUpInMessage();
Conduit backChannel=destination.getBackChannel(inMessage);
assertNotNull("expected back channel",backChannel);
assertEquals("unexpected target",EndpointReferenceUtils.ANONYMOUS_ADDRESS,backChannel.getTarget().getAddress().getValue());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testMultiplexGetIdForAddress() throws Exception {
destination=setUpDestination();
destination.setMultiplexWithAddress(true);
final String id="ID3";
EndpointReferenceType refWithId=destination.getAddressWithId(id);
String pathInfo=EndpointReferenceUtils.getAddress(refWithId);
Map context=new HashMap();
assertNull("fails with no context",destination.getId(context));
context.put(Message.PATH_INFO,pathInfo);
String result=destination.getId(context);
assertNotNull(result);
assertEquals("match our id",result,id);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetAddress() throws Exception {
destination=setUpDestination();
EndpointReferenceType ref=destination.getAddress();
assertNotNull("unexpected null address",ref);
assertEquals("unexpected address",EndpointReferenceUtils.getAddress(ref),StringUtils.addDefaultPortIfMissing(EndpointReferenceUtils.getAddress(address)));
assertEquals("unexpected service name local part",EndpointReferenceUtils.getServiceName(ref,bus).getLocalPart(),"Service");
assertEquals("unexpected portName",EndpointReferenceUtils.getPortName(ref),"Port");
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testMultiplexGetAddressWithId() throws Exception {
destination=setUpDestination();
final String id="ID2";
EndpointReferenceType refWithId=destination.getAddressWithId(id);
assertNotNull(refWithId);
assertNotNull(refWithId.getReferenceParameters());
assertNotNull(refWithId.getReferenceParameters().getAny());
assertTrue("it is an element",refWithId.getReferenceParameters().getAny().get(0) instanceof JAXBElement);
JAXBElement> el=(JAXBElement>)refWithId.getReferenceParameters().getAny().get(0);
assertEquals("match our id",el.getValue(),id);
}
InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testGetMultiple() throws Exception {
transportFactory=new HTTPTransportFactory();
bus=BusFactory.getDefaultBus();
ServiceInfo serviceInfo=new ServiceInfo();
serviceInfo.setName(new QName("bla","Service"));
EndpointInfo ei=new EndpointInfo(serviceInfo,"");
ei.setName(new QName("bla","Port"));
ei.setAddress("http://foo");
Destination d1=transportFactory.getDestination(ei,bus);
Destination d2=transportFactory.getDestination(ei,bus);
assertEquals(d1,d2);
d2.shutdown();
Destination d3=transportFactory.getDestination(ei,bus);
assertNotSame(d1,d3);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testMultiplexGetId() throws Exception {
destination=setUpDestination();
final String id="ID3";
EndpointReferenceType refWithId=destination.getAddressWithId(id);
Map context=new HashMap();
assertNull("fails with no context",destination.getId(context));
AddressingProperties maps=EasyMock.createMock(AddressingProperties.class);
maps.getToEndpointReference();
EasyMock.expectLastCall().andReturn(refWithId);
EasyMock.replay(maps);
context.put(JAXWSAConstants.ADDRESSING_PROPERTIES_INBOUND,maps);
String result=destination.getId(context);
assertNotNull(result);
assertEquals("match our id",result,id);
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testMultiplexGetAddressWithIdForAddress() throws Exception {
destination=setUpDestination();
destination.setMultiplexWithAddress(true);
final String id="ID3";
EndpointReferenceType refWithId=destination.getAddressWithId(id);
assertNotNull(refWithId);
assertNull(refWithId.getReferenceParameters());
assertTrue("match our id",EndpointReferenceUtils.getAddress(refWithId).indexOf(id) != -1);
}
InternalCallVerifier NullVerifier
@Test public void testContinuationsIgnored() throws Exception {
HttpServletRequest httpRequest=EasyMock.createMock(HttpServletRequest.class);
ServiceInfo serviceInfo=new ServiceInfo();
serviceInfo.setName(new QName("bla","Service"));
EndpointInfo ei=new EndpointInfo(serviceInfo,"");
ei.setName(new QName("bla","Port"));
final NettyHttpServerEngine httpEngine=new NettyHttpServerEngine("localhost",8080);
NettyHttpServerEngineFactory factory=new NettyHttpServerEngineFactory(){
@Override public NettyHttpServerEngine retrieveNettyHttpServerEngine( int port){
return httpEngine;
}
}
;
transportFactory=new HTTPTransportFactory();
bus=BusFactory.getDefaultBus();
bus.setExtension(factory,NettyHttpServerEngineFactory.class);
TestJettyDestination testDestination=new TestJettyDestination(bus,transportFactory.getRegistry(),ei,factory);
testDestination.finalizeConfig();
Message mi=testDestination.retrieveFromContinuation(httpRequest);
assertNull("Continuations must be ignored",mi);
}
BooleanVerifier InternalCallVerifier
@Test public void testRandomPortAllocation() throws Exception {
bus=BusFactory.getDefaultBus();
transportFactory=new HTTPTransportFactory();
ServiceInfo serviceInfo=new ServiceInfo();
serviceInfo.setName(new QName("bla","Service"));
EndpointInfo ei=new EndpointInfo(serviceInfo,"");
ei.setName(new QName("bla","Port"));
Destination d1=transportFactory.getDestination(ei,bus);
URL url=new URL(d1.getAddress().getAddress().getValue());
assertTrue("No random port has been allocated",url.getPort() > 0);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testDoServiceWithHttpGET() throws Exception {
destination=setUpDestination(false,false);
setUpDoService(false,false,false,"GET","?customerId=abc&cutomerAdd=def",200);
destination.doService(request,response);
assertNotNull("unexpected null message",inMessage);
assertEquals("unexpected method",inMessage.get(Message.HTTP_REQUEST_METHOD),"GET");
assertEquals("unexpected path",inMessage.get(Message.PATH_INFO),"/bar/foo");
assertEquals("unexpected query",inMessage.get(Message.QUERY_STRING),"?customerId=abc&cutomerAdd=def");
}
InternalCallVerifier EqualityVerifier
@Test public void testServerPolicyInServiceModel() throws Exception {
policy=new HTTPServerPolicy();
address=getEPR("bar/foo");
bus=new ExtensionManagerBus();
transportFactory=new HTTPTransportFactory();
ServiceInfo serviceInfo=new ServiceInfo();
serviceInfo.setName(new QName("bla","Service"));
endpointInfo=new EndpointInfo(serviceInfo,"");
endpointInfo.setName(new QName("bla","Port"));
endpointInfo.addExtensor(policy);
engine=EasyMock.createMock(NettyHttpServerEngine.class);
EasyMock.replay();
endpointInfo.setAddress(NOWHERE + "bar/foo");
NettyHttpDestination dest=new EasyMockJettyHTTPDestination(bus,transportFactory.getRegistry(),endpointInfo,null,engine);
assertEquals(policy,dest.getServer());
}
Class: org.apache.cxf.transport.http.netty.server.NettyHttpServerEngineFactoryTest BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testTransportFactoryHasEngineFactory() throws Exception {
bus=BusFactory.getDefaultBus(true);
assertNotNull("Cannot get bus",bus);
DestinationFactoryManager destFM=bus.getExtension(DestinationFactoryManager.class);
assertNotNull("Cannot get DestinationFactoryManager",destFM);
DestinationFactory destF=destFM.getDestinationFactory("http://cxf.apache.org/transports/http");
assertNotNull("No DestinationFactory",destF);
assertTrue(HTTPTransportFactory.class.isInstance(destF));
NettyHttpServerEngineFactory factory=bus.getExtension(NettyHttpServerEngineFactory.class);
assertNotNull("EngineFactory is not configured.",factory);
}
Class: org.apache.cxf.transport.http.netty.server.NettyHttpServerEngineTest BooleanVerifier InternalCallVerifier
@Test public void testEngineRetrieval() throws Exception {
NettyHttpServerEngine engine=factory.createNettyHttpServerEngine(PORT1,"http");
assertTrue("Engine references for the same port should point to the same instance",engine == factory.retrieveNettyHttpServerEngine(PORT1));
NettyHttpServerEngineFactory.destroyForPort(PORT1);
}
Class: org.apache.cxf.transport.http.netty.server.integration.NettyServerTest InternalCallVerifier EqualityVerifier
@Test public void testInvocation() throws Exception {
updateAddressPort(g,PORT);
String response=g.greetMe("test");
assertEquals("Get a wrong response","Hello test",response);
}
Class: org.apache.cxf.transport.http.netty.server.integration.SSLNettyServerTest InternalCallVerifier EqualityVerifier
@Test public void testInvocation() throws Exception {
setupTLS(g);
setAddress(g,address);
String response=g.greetMe("test");
assertEquals("Get a wrong response","Hello test",response);
}
Class: org.apache.cxf.transport.http.policy.ClientPolicyCalculatorTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testIntersectClientPolicies(){
ClientPolicyCalculator calc=new ClientPolicyCalculator();
HTTPClientPolicy p1=new HTTPClientPolicy();
HTTPClientPolicy p2=new HTTPClientPolicy();
HTTPClientPolicy p=null;
p1.setBrowserType("browser");
p=calc.intersect(p1,p2);
assertEquals("browser",p.getBrowserType());
p1.setBrowserType(null);
p1.setConnectionTimeout(10000L);
p=calc.intersect(p1,p2);
assertEquals(10000L,p.getConnectionTimeout());
p1.setAllowChunking(false);
p2.setAllowChunking(false);
p=calc.intersect(p1,p2);
assertTrue(!p.isAllowChunking());
}
InternalCallVerifier EqualityVerifier
@Test public void testLongTimeouts(){
ClientPolicyCalculator calc=new ClientPolicyCalculator();
HTTPClientPolicy p1=new HTTPClientPolicy();
HTTPClientPolicy p2=new HTTPClientPolicy();
p2.setReceiveTimeout(120000);
p2.setConnectionTimeout(60000);
HTTPClientPolicy p=calc.intersect(p1,p2);
assertEquals(120000,p.getReceiveTimeout());
assertEquals(60000,p.getConnectionTimeout());
p1=new HTTPClientPolicy();
p2=new HTTPClientPolicy();
p1.setReceiveTimeout(120000);
p1.setConnectionTimeout(60000);
p=calc.intersect(p1,p2);
assertEquals(120000,p.getReceiveTimeout());
assertEquals(60000,p.getConnectionTimeout());
p2.setReceiveTimeout(50000);
p2.setConnectionTimeout(20000);
p=calc.intersect(p1,p2);
assertEquals(120000,p.getReceiveTimeout());
assertEquals(60000,p.getConnectionTimeout());
p=calc.intersect(p2,p1);
assertEquals(50000,p.getReceiveTimeout());
assertEquals(20000,p.getConnectionTimeout());
}
BooleanVerifier InternalCallVerifier
@Test public void testCompatibleClientPolicies(){
ClientPolicyCalculator calc=new ClientPolicyCalculator();
HTTPClientPolicy p1=new HTTPClientPolicy();
assertTrue("Policy is not compatible with itself.",calc.compatible(p1,p1));
HTTPClientPolicy p2=new HTTPClientPolicy();
assertTrue("Policies are not compatible.",calc.compatible(p1,p2));
p1.setBrowserType("browser");
assertTrue("Policies are not compatible.",calc.compatible(p1,p2));
p1.setBrowserType(null);
p1.setConnectionTimeout(10000);
assertTrue("Policies are not compatible.",calc.compatible(p1,p2));
p1.setAllowChunking(false);
assertTrue("Policies are compatible.",!calc.compatible(p1,p2));
p2.setAllowChunking(false);
assertTrue("Policies are compatible.",calc.compatible(p1,p2));
}
BooleanVerifier InternalCallVerifier
@Test public void testEqualClientPolicies(){
ClientPolicyCalculator calc=new ClientPolicyCalculator();
HTTPClientPolicy p1=new HTTPClientPolicy();
assertTrue(calc.equals(p1,p1));
HTTPClientPolicy p2=new HTTPClientPolicy();
assertTrue(calc.equals(p1,p2));
p1.setDecoupledEndpoint("http://localhost:8080/decoupled");
assertTrue(!calc.equals(p1,p2));
p2.setDecoupledEndpoint("http://localhost:8080/decoupled");
assertTrue(calc.equals(p1,p2));
p1.setReceiveTimeout(10000L);
assertTrue(!calc.equals(p1,p2));
}
Class: org.apache.cxf.transport.http.policy.HTTPClientAssertionBuilderTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testBuildAssertion() throws Exception {
HTTPClientAssertionBuilder ab=new HTTPClientAssertionBuilder();
Assertion a=ab.buildAssertion();
assertTrue(a instanceof JaxbAssertion);
assertTrue(a instanceof HTTPClientAssertionBuilder.HTTPClientPolicyAssertion);
assertEquals(new ClientPolicyCalculator().getDataClassName(),a.getName());
assertTrue(!a.isOptional());
}
BooleanVerifier InternalCallVerifier
@Test public void testHTTPCLientPolicyAssertionEqual() throws Exception {
HTTPClientAssertionBuilder ab=new HTTPClientAssertionBuilder();
JaxbAssertion a=ab.buildAssertion();
a.setData(new HTTPClientPolicy());
assertTrue(a.equal(a));
JaxbAssertion b=ab.buildAssertion();
b.setData(new HTTPClientPolicy());
assertTrue(a.equal(b));
HTTPClientPolicy pa=new HTTPClientPolicy();
a.setData(pa);
assertTrue(a.equal(a));
HTTPClientPolicy pb=new HTTPClientPolicy();
b.setData(pb);
assertTrue(a.equal(b));
pa.setDecoupledEndpoint("http://localhost:9999/decoupled_endpoint");
assertTrue(!a.equal(b));
}
Class: org.apache.cxf.transport.http.policy.HTTPServerAssertionBuilderTest BooleanVerifier InternalCallVerifier
@Test public void testHTTPServerPolicyAssertionEqual() throws Exception {
HTTPServerAssertionBuilder ab=new HTTPServerAssertionBuilder();
JaxbAssertion a=ab.buildAssertion();
a.setData(new HTTPServerPolicy());
assertTrue(a.equal(a));
JaxbAssertion b=ab.buildAssertion();
b.setData(new HTTPServerPolicy());
assertTrue(a.equal(b));
HTTPServerPolicy pa=new HTTPServerPolicy();
a.setData(pa);
assertTrue(a.equal(a));
HTTPServerPolicy pb=new HTTPServerPolicy();
b.setData(pb);
assertTrue(a.equal(b));
pa.setSuppressClientSendErrors(true);
assertTrue(!a.equal(b));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testBuildAssertion() throws Exception {
HTTPServerAssertionBuilder ab=new HTTPServerAssertionBuilder();
Assertion a=ab.buildAssertion();
assertTrue(a instanceof JaxbAssertion);
assertTrue(a instanceof HTTPServerAssertionBuilder.HTTPServerPolicyAssertion);
assertEquals(new ServerPolicyCalculator().getDataClassName(),a.getName());
assertTrue(!a.isOptional());
}
Class: org.apache.cxf.transport.http.policy.ServerPolicyCalculatorTest BooleanVerifier InternalCallVerifier
@Test public void testCompatibleServerPolicies(){
ServerPolicyCalculator spc=new ServerPolicyCalculator();
HTTPServerPolicy p1=new HTTPServerPolicy();
assertTrue("Policy is not compatible with itself.",spc.compatible(p1,p1));
HTTPServerPolicy p2=new HTTPServerPolicy();
assertTrue("Policies are not compatible.",spc.compatible(p1,p2));
p1.setServerType("server");
assertTrue("Policies are not compatible.",spc.compatible(p1,p2));
p1.setServerType(null);
p1.setReceiveTimeout(10000);
assertTrue("Policies are not compatible.",spc.compatible(p1,p2));
p1.setSuppressClientSendErrors(false);
assertTrue("Policies are compatible.",spc.compatible(p1,p2));
p1.setSuppressClientSendErrors(true);
assertTrue("Policies are compatible.",!spc.compatible(p1,p2));
p2.setSuppressClientSendErrors(true);
assertTrue("Policies are compatible.",spc.compatible(p1,p2));
}
BooleanVerifier InternalCallVerifier
@Test public void testEqualServerPolicies(){
ServerPolicyCalculator spc=new ServerPolicyCalculator();
HTTPServerPolicy p1=new HTTPServerPolicy();
assertTrue(spc.equals(p1,p1));
HTTPServerPolicy p2=new HTTPServerPolicy();
assertTrue(spc.equals(p1,p2));
p1.setContentEncoding("encoding");
assertTrue(!spc.equals(p1,p2));
p2.setContentEncoding("encoding");
assertTrue(spc.equals(p1,p2));
p1.setSuppressClientSendErrors(true);
assertTrue(!spc.equals(p1,p2));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testIntersectServerPolicies(){
ServerPolicyCalculator spc=new ServerPolicyCalculator();
HTTPServerPolicy p1=new HTTPServerPolicy();
HTTPServerPolicy p2=new HTTPServerPolicy();
HTTPServerPolicy p=null;
p1.setServerType("server");
p=spc.intersect(p1,p2);
assertEquals("server",p.getServerType());
p1.setServerType(null);
p1.setReceiveTimeout(10000L);
p=spc.intersect(p1,p2);
assertEquals(10000L,p.getReceiveTimeout());
p1.setSuppressClientSendErrors(true);
p2.setSuppressClientSendErrors(true);
p=spc.intersect(p1,p2);
assertTrue(p.isSuppressClientSendErrors());
}
Class: org.apache.cxf.transport.http_jaxws_spi.JAXWSHttpSpiDestinationTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCtor() throws Exception {
control.replay();
JAXWSHttpSpiDestination destination=new JAXWSHttpSpiDestination(bus,new DestinationRegistryImpl(),endpoint);
assertNull(destination.getMessageObserver());
assertNotNull(destination.getAddress());
assertNotNull(destination.getAddress().getAddress());
assertEquals(ADDRESS,destination.getAddress().getAddress().getValue());
}
Class: org.apache.cxf.transport.http_jetty.JettyHTTPDestinationTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetAddress() throws Exception {
destination=setUpDestination();
EndpointReferenceType ref=destination.getAddress();
assertNotNull("unexpected null address",ref);
assertEquals("unexpected address",EndpointReferenceUtils.getAddress(ref),StringUtils.addDefaultPortIfMissing(EndpointReferenceUtils.getAddress(address)));
assertEquals("unexpected service name local part",EndpointReferenceUtils.getServiceName(ref,bus).getLocalPart(),"Service");
assertEquals("unexpected portName",EndpointReferenceUtils.getPortName(ref),"Port");
}
InternalCallVerifier EqualityVerifier
@Test public void testServerPolicyInServiceModel() throws Exception {
policy=new HTTPServerPolicy();
address=getEPR("bar/foo");
bus=BusFactory.getDefaultBus(true);
transportFactory=new HTTPTransportFactory();
ServiceInfo serviceInfo=new ServiceInfo();
serviceInfo.setName(new QName("bla","Service"));
endpointInfo=new EndpointInfo(serviceInfo,"");
endpointInfo.setName(new QName("bla","Port"));
endpointInfo.addExtensor(policy);
engine=EasyMock.createMock(JettyHTTPServerEngine.class);
EasyMock.replay();
endpointInfo.setAddress(NOWHERE + "bar/foo");
JettyHTTPDestination dest=new EasyMockJettyHTTPDestination(bus,transportFactory.getRegistry(),endpointInfo,null,engine);
assertEquals(policy,dest.getServer());
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testMultiplexGetAddressWithId() throws Exception {
destination=setUpDestination();
final String id="ID2";
EndpointReferenceType refWithId=destination.getAddressWithId(id);
assertNotNull(refWithId);
assertNotNull(refWithId.getReferenceParameters());
assertNotNull(refWithId.getReferenceParameters().getAny());
assertTrue("it is an element",refWithId.getReferenceParameters().getAny().get(0) instanceof JAXBElement);
JAXBElement> el=(JAXBElement>)refWithId.getReferenceParameters().getAny().get(0);
assertEquals("match our id",el.getValue(),id);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testMultiplexGetId() throws Exception {
destination=setUpDestination();
final String id="ID3";
EndpointReferenceType refWithId=destination.getAddressWithId(id);
Map context=new HashMap();
assertNull("fails with no context",destination.getId(context));
AddressingProperties maps=EasyMock.createMock(AddressingProperties.class);
maps.getToEndpointReference();
EasyMock.expectLastCall().andReturn(refWithId);
EasyMock.replay(maps);
context.put(JAXWSAConstants.ADDRESSING_PROPERTIES_INBOUND,maps);
String result=destination.getId(context);
assertNotNull(result);
assertEquals("match our id",result,id);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testDoServiceWithHttpGET() throws Exception {
destination=setUpDestination(false,false);
setUpDoService(false,false,false,"GET","?customerId=abc&cutomerAdd=def",200);
destination.doService(request,response);
assertNotNull("unexpected null message",inMessage);
assertEquals("unexpected method",inMessage.get(Message.HTTP_REQUEST_METHOD),"GET");
assertEquals("unexpected path",inMessage.get(Message.PATH_INFO),"/bar/foo");
assertEquals("unexpected query",inMessage.get(Message.QUERY_STRING),"?customerId=abc&cutomerAdd=def");
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testMultiplexGetAddressWithIdForAddress() throws Exception {
destination=setUpDestination();
destination.setMultiplexWithAddress(true);
final String id="ID3";
EndpointReferenceType refWithId=destination.getAddressWithId(id);
assertNotNull(refWithId);
assertNull(refWithId.getReferenceParameters());
assertTrue("match our id",EndpointReferenceUtils.getAddress(refWithId).indexOf(id) != -1);
}
BooleanVerifier InternalCallVerifier
@Test public void testRandomPortAllocation() throws Exception {
bus=BusFactory.getDefaultBus(true);
transportFactory=new HTTPTransportFactory();
ServiceInfo serviceInfo=new ServiceInfo();
serviceInfo.setName(new QName("bla","Service"));
EndpointInfo ei=new EndpointInfo(serviceInfo,"");
ei.setName(new QName("bla","Port"));
Destination d1=transportFactory.getDestination(ei,bus);
URL url=new URL(d1.getAddress().getAddress().getValue());
assertTrue("No random port has been allocated",url.getPort() > 0);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetAnonBackChannel() throws Exception {
destination=setUpDestination(false,false);
setUpDoService(false);
destination.doService(request,response);
setUpInMessage();
Conduit backChannel=destination.getBackChannel(inMessage);
assertNotNull("expected back channel",backChannel);
assertEquals("unexpected target",EndpointReferenceUtils.ANONYMOUS_ADDRESS,backChannel.getTarget().getAddress().getValue());
}
InternalCallVerifier NullVerifier
@Test public void testContinuationsIgnored() throws Exception {
HttpServletRequest httpRequest=EasyMock.createMock(HttpServletRequest.class);
ServiceInfo serviceInfo=new ServiceInfo();
serviceInfo.setName(new QName("bla","Service"));
EndpointInfo ei=new EndpointInfo(serviceInfo,"");
ei.setName(new QName("bla","Port"));
final JettyHTTPServerEngine httpEngine=new JettyHTTPServerEngine();
httpEngine.setContinuationsEnabled(false);
JettyHTTPServerEngineFactory factory=new JettyHTTPServerEngineFactory(){
@Override public JettyHTTPServerEngine retrieveJettyHTTPServerEngine( int port){
return httpEngine;
}
}
;
Bus b2=new ExtensionManagerBus();
transportFactory=new HTTPTransportFactory();
b2.setExtension(factory,JettyHTTPServerEngineFactory.class);
TestJettyDestination testDestination=new TestJettyDestination(b2,transportFactory.getRegistry(),ei,factory);
testDestination.finalizeConfig();
Message mi=testDestination.retrieveFromContinuation(httpRequest);
assertNull("Continuations must be ignored",mi);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testMultiplexGetIdForAddress() throws Exception {
destination=setUpDestination();
destination.setMultiplexWithAddress(true);
final String id="ID3";
EndpointReferenceType refWithId=destination.getAddressWithId(id);
String pathInfo=EndpointReferenceUtils.getAddress(refWithId);
Map context=new HashMap();
assertNull("fails with no context",destination.getId(context));
context.put(Message.PATH_INFO,pathInfo);
String result=destination.getId(context);
assertNotNull(result);
assertEquals("match our id",result,id);
}
InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testGetMultiple() throws Exception {
bus=BusFactory.getDefaultBus(true);
transportFactory=new HTTPTransportFactory();
ServiceInfo serviceInfo=new ServiceInfo();
serviceInfo.setName(new QName("bla","Service"));
EndpointInfo ei=new EndpointInfo(serviceInfo,"");
ei.setName(new QName("bla","Port"));
ei.setAddress("http://foo");
Destination d1=transportFactory.getDestination(ei,bus);
Destination d2=transportFactory.getDestination(ei,bus);
assertEquals(d1,d2);
d2.shutdown();
Destination d3=transportFactory.getDestination(ei,bus);
assertNotSame(d1,d3);
}
Class: org.apache.cxf.transport.http_jetty.JettyHTTPServerEngineFactoryTest BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
/**
* This test makes sure that a default Spring initialized bus will
* have the JettyHTTPServerEngineFactory (absent of
* configuration.
*/
@Test public void testMakeSureTransportFactoryHasEngineFactory() throws Exception {
bus=BusFactory.getDefaultBus(true);
assertNotNull("Cannot get bus",bus);
DestinationFactoryManager destFM=bus.getExtension(DestinationFactoryManager.class);
assertNotNull("Cannot get DestinationFactoryManager",destFM);
DestinationFactory destF=destFM.getDestinationFactory("http://cxf.apache.org/transports/http");
assertNotNull("No DestinationFactory",destF);
assertTrue(HTTPTransportFactory.class.isInstance(destF));
JettyHTTPServerEngineFactory factory=bus.getExtension(JettyHTTPServerEngineFactory.class);
assertNotNull("EngineFactory is not configured.",factory);
}
InternalCallVerifier NullVerifier
@Test public void testAnInvalidConfiguresfile(){
URL config=getClass().getResource("invalid-engines.xml");
bus=new SpringBusFactory().createBus(config);
JettyHTTPServerEngineFactory factory=bus.getExtension(JettyHTTPServerEngineFactory.class);
assertNotNull("EngineFactory is not configured.",factory);
}
UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
/**
* This test makes sure that with a
* that the bus is configured with the rightly configured Jetty
* HTTP Server Engine Factory. Port 1234 should have be configured
* for TLS.
*/
@Test public void testMakeSureTransportFactoryHasEngineFactoryConfigured() throws Exception {
URL config=getClass().getResource("server-engine-factory.xml");
bus=new SpringBusFactory().createBus(config,true);
JettyHTTPServerEngineFactory factory=bus.getExtension(JettyHTTPServerEngineFactory.class);
assertNotNull("EngineFactory is not configured.",factory);
JettyHTTPServerEngine engine=null;
engine=factory.createJettyHTTPServerEngine(1234,"https");
assertNotNull("Engine is not available.",engine);
assertEquals(1234,engine.getPort());
assertEquals("Not https","https",engine.getProtocol());
try {
engine=factory.createJettyHTTPServerEngine(1234,"http");
fail("The engine's protocol should be https");
}
catch ( Exception e) {
}
}
Class: org.apache.cxf.transport.http_jetty.JettyHTTPServerEngineTest BooleanVerifier InternalCallVerifier
/**
* Check that names of threads serving requests for instances of JettyHTTPServerEngine
* can be set with user specified name.
*/
@Test public void testSettingThreadNames() throws Exception {
String threadNamePrefix1="TestPrefix";
JettyHTTPServerEngine engine=factory.createJettyHTTPServerEngine(PORT1,"http");
ThreadingParameters parameters=new ThreadingParameters();
parameters.setThreadNamePrefix(threadNamePrefix1);
engine.setThreadingParameters(parameters);
engine.finalizeConfig();
JettyHTTPTestHandler handler=new JettyHTTPTestHandler("string1",true);
engine.addServant(new URL("https://localhost:" + PORT1 + "/test"),handler);
assertTrue("No threads whose name is started with " + threadNamePrefix1,checkForExistenceOfThreads(threadNamePrefix1));
engine=factory.createJettyHTTPServerEngine(PORT3,"http");
engine.finalizeConfig();
handler=new JettyHTTPTestHandler("string3",true);
engine.addServant(new URL("https://localhost:" + PORT3 + "/test"),handler);
ThreadPool threadPool=engine.getServer().getThreadPool();
QueuedThreadPool qtp=(QueuedThreadPool)threadPool;
String prefixDefault=qtp.getName();
assertTrue("No threads whose name is started with " + prefixDefault,checkForExistenceOfThreads(prefixDefault));
String threadNamePrefix2="AnotherPrefix";
engine=factory.createJettyHTTPServerEngine(PORT2,"http");
parameters=new ThreadingParameters();
parameters.setThreadNamePrefix(threadNamePrefix2);
engine.setThreadingParameters(parameters);
engine.finalizeConfig();
handler=new JettyHTTPTestHandler("string2",true);
engine.addServant(new URL("https://localhost:" + PORT2 + "/test"),handler);
assertTrue("No threads whose name is started with " + threadNamePrefix2,checkForExistenceOfThreads(threadNamePrefix2));
JettyHTTPServerEngineFactory.destroyForPort(PORT1);
JettyHTTPServerEngineFactory.destroyForPort(PORT2);
JettyHTTPServerEngineFactory.destroyForPort(PORT3);
}
APIUtilityVerifier UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetContextHandler() throws Exception {
String urlStr="http://localhost:" + PORT1 + "/hello/test";
JettyHTTPServerEngine engine=factory.createJettyHTTPServerEngine(PORT1,"http");
ContextHandler contextHandler=engine.getContextHandler(new URL(urlStr));
assertNull(contextHandler);
JettyHTTPTestHandler handler1=new JettyHTTPTestHandler("string1",true);
JettyHTTPTestHandler handler2=new JettyHTTPTestHandler("string2",true);
engine.addServant(new URL(urlStr),handler1);
contextHandler=engine.getContextHandler(new URL(urlStr));
contextHandler.stop();
contextHandler.setHandler(handler2);
contextHandler.start();
String response=null;
try {
response=getResponse(urlStr);
}
catch ( Exception ex) {
fail("Can't get the reponse from the server " + ex);
}
assertEquals("the jetty http handler did not take effect",response,"string2");
JettyHTTPServerEngineFactory.destroyForPort(PORT1);
}
UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testJettyHTTPHandler() throws Exception {
String urlStr1="http://localhost:" + PORT3 + "/hello/test1";
String urlStr2="http://localhost:" + PORT3 + "/hello/test2";
JettyHTTPServerEngine engine=factory.createJettyHTTPServerEngine(PORT3,"http");
ContextHandler contextHandler=engine.getContextHandler(new URL(urlStr1));
assertNull(contextHandler);
JettyHTTPHandler handler1=new JettyHTTPTestHandler("test",false);
JettyHTTPHandler handler2=new JettyHTTPTestHandler("test2",false);
engine.addServant(new URL(urlStr1),handler1);
contextHandler=engine.getContextHandler(new URL(urlStr1));
engine.addServant(new URL(urlStr2),handler2);
contextHandler=engine.getContextHandler(new URL(urlStr2));
String response=null;
try {
response=getResponse(urlStr1 + "/test");
}
catch ( Exception ex) {
fail("Can't get the reponse from the server " + ex);
}
assertEquals("the jetty http handler did not take effect",response,"test");
try {
response=getResponse(urlStr2 + "/test");
}
catch ( Exception ex) {
fail("Can't get the reponse from the server " + ex);
}
assertEquals("the jetty http handler did not take effect",response,"test2");
JettyHTTPServerEngineFactory.destroyForPort(PORT3);
}
APIUtilityVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testaddServants() throws Exception {
String urlStr="http://localhost:" + PORT1 + "/hello/test";
String urlStr2="http://localhost:" + PORT1 + "/hello233/test";
JettyHTTPServerEngine engine=factory.createJettyHTTPServerEngine(PORT1,"http");
engine.setMaxIdleTime(30000);
engine.addServant(new URL(urlStr),new JettyHTTPTestHandler("string1",true));
assertEquals("Get the wrong maxIdleTime.",30000,getMaxIdle(engine.getConnector()));
String response=null;
response=getResponse(urlStr);
assertEquals("The jetty http handler did not take effect",response,"string1");
try {
engine.addServant(new URL(urlStr),new JettyHTTPTestHandler("string2",true));
fail("We don't support to publish the two service at the same context path");
}
catch ( Exception ex) {
assertTrue("Get a wrong exception message",ex.getMessage().indexOf("hello/test") > 0);
}
try {
engine.addServant(new URL(urlStr + "/test"),new JettyHTTPTestHandler("string2",true));
fail("We don't support to publish the two service at the same context path");
}
catch ( Exception ex) {
assertTrue("Get a wrong exception message",ex.getMessage().indexOf("hello/test/test") > 0);
}
try {
engine.addServant(new URL("http://localhost:" + PORT1 + "/hello"),new JettyHTTPTestHandler("string2",true));
fail("We don't support to publish the two service at the same context path");
}
catch ( Exception ex) {
assertTrue("Get a wrong exception message",ex.getMessage().indexOf("hello") > 0);
}
System.setProperty("org.apache.cxf.transports.http_jetty.DontCheckUrl","true");
engine.addServant(new URL(urlStr + "/test"),new JettyHTTPTestHandler("string2",true));
System.clearProperty("org.apache.cxf.transports.http_jetty.DontCheckUrl");
engine.addServant(new URL(urlStr2),new JettyHTTPTestHandler("string2",true));
Set s=CastUtils.cast(ManagementFactory.getPlatformMBeanServer().queryNames(new ObjectName("org.eclipse.jetty.server:type=server,*"),null));
assertEquals("Could not find 1 Jetty Server: " + s,1,s.size());
engine.removeServant(new URL(urlStr));
engine.shutdown();
response=getResponse(urlStr2);
assertEquals("The jetty http handler did not take effect",response,"string2");
JettyHTTPServerEngineFactory.destroyForPort(PORT1);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testHttpAndHttps() throws Exception {
JettyHTTPServerEngine engine=factory.createJettyHTTPServerEngine(PORT1,"http");
assertTrue("Protocol must be http","http".equals(engine.getProtocol()));
engine=new JettyHTTPServerEngine();
engine.setPort(PORT2);
engine.setMaxIdleTime(30000);
engine.setTlsServerParameters(new TLSServerParameters());
engine.finalizeConfig();
List list=new ArrayList();
list.add(engine);
factory.setEnginesList(list);
engine=factory.createJettyHTTPServerEngine(PORT2,"https");
JettyHTTPTestHandler handler1=new JettyHTTPTestHandler("string1",true);
engine.addServant(new URL("https://localhost:" + PORT2 + "/test"),handler1);
assertTrue("Protocol must be https","https".equals(engine.getProtocol()));
assertEquals("Get the wrong maxIdleTime.",30000,getMaxIdle(engine.getConnector()));
factory.setTLSServerParametersForPort(PORT1,new TLSServerParameters());
engine=factory.createJettyHTTPServerEngine(PORT1,"https");
assertTrue("Protocol must be https","https".equals(engine.getProtocol()));
factory.setTLSServerParametersForPort(PORT3,new TLSServerParameters());
engine=factory.createJettyHTTPServerEngine(PORT3,"https");
assertTrue("Protocol must be https","https".equals(engine.getProtocol()));
JettyHTTPServerEngineFactory.destroyForPort(PORT1);
JettyHTTPServerEngineFactory.destroyForPort(PORT2);
JettyHTTPServerEngineFactory.destroyForPort(PORT3);
}
BooleanVerifier InternalCallVerifier
@Test public void testEngineRetrieval() throws Exception {
JettyHTTPServerEngine engine=factory.createJettyHTTPServerEngine(PORT1,"http");
assertTrue("Engine references for the same port should point to the same instance",engine == factory.retrieveJettyHTTPServerEngine(PORT1));
JettyHTTPServerEngineFactory.destroyForPort(PORT1);
}
Class: org.apache.cxf.transport.http_jetty.spring.BeanDefinitionParsersTest InternalCallVerifier EqualityVerifier
@Test public void testDest() throws Exception {
BeanDefinitionBuilder bd=BeanDefinitionBuilder.childBeanDefinition("child");
HttpDestinationBeanDefinitionParser parser=new HttpDestinationBeanDefinitionParser();
Document d=StaxUtils.read(getClass().getResourceAsStream("destination.xml"));
parser.doParse(d.getDocumentElement(),null,bd);
PropertyValue[] pvs=bd.getRawBeanDefinition().getPropertyValues().getPropertyValues();
assertEquals(2,pvs.length);
assertEquals("foobar",((HTTPServerPolicy)pvs[0].getValue()).getContentEncoding());
assertEquals("exact",pvs[1].getValue());
}
InternalCallVerifier EqualityVerifier
@Test public void testConduit() throws Exception {
BeanDefinitionBuilder bd=BeanDefinitionBuilder.childBeanDefinition("child");
HttpConduitBeanDefinitionParser parser=new HttpConduitBeanDefinitionParser();
Document d=StaxUtils.read(getClass().getResourceAsStream("conduit.xml"));
parser.doParse(d.getDocumentElement(),null,bd);
PropertyValue[] pvs=bd.getRawBeanDefinition().getPropertyValues().getPropertyValues();
assertEquals(1,pvs.length);
assertEquals(97,((HTTPClientPolicy)pvs[0].getValue()).getConnectionTimeout(),0);
}
Class: org.apache.cxf.transport.jms.JMSConduitTest BooleanVerifier InternalCallVerifier
@Test public void testPrepareSend() throws Exception {
EndpointInfo ei=setupServiceInfo("http://cxf.apache.org/hello_world_jms",WSDL,"HelloWorldService","HelloWorldPort");
JMSConduit conduit=setupJMSConduit(ei);
Message message=new MessageImpl();
conduit.prepare(message);
OutputStream os=message.getContent(OutputStream.class);
Writer writer=message.getContent(Writer.class);
assertTrue("The OutputStream and Writer should not both be null ",os != null || writer != null);
conduit.close();
}
Class: org.apache.cxf.transport.jms.JMSConfigFactoryTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testUsernameAndPassword() throws Exception {
EndpointInfo ei=setupServiceInfo("HelloWorldService","HelloWorldPort");
JMSConfiguration config=JMSConfigFactory.createFromEndpointInfo(bus,ei,target);
Assert.assertEquals("User name does not match.","testUser",config.getUserName());
Assert.assertEquals("Password does not match.","testPassword",config.getPassword());
}
Class: org.apache.cxf.transport.jms.JMSDestinationTest APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testIsMultiplexCapable() throws Exception {
EndpointInfo ei=setupServiceInfo("HelloWorldService","HelloWorldPort");
final JMSDestination destination=setupJMSDestination(ei);
destination.setMessageObserver(createMessageObserver());
assertTrue("is multiplex",destination instanceof MultiplexDestination);
destination.shutdown();
}
InternalCallVerifier NullVerifier
@Test public void testRoundTripDestinationDoNotCreateSecurityContext() throws Exception {
Message msg=testRoundTripDestination(false);
SecurityContext securityContext=msg.get(SecurityContext.class);
assertNull("SecurityContext should not be set in message received by JMSDestination",securityContext);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testRoundTripDestination() throws Exception {
Message msg=testRoundTripDestination(true);
SecurityContext securityContext=msg.get(SecurityContext.class);
assertNotNull("SecurityContext should be set in message received by JMSDestination",securityContext);
assertEquals("Principal in SecurityContext should be","testUser",securityContext.getUserPrincipal().getName());
}
Class: org.apache.cxf.transport.jms.ThrottlingCounterTest BooleanVerifier InternalCallVerifier
@Test public void testThrottleWithJmsStartAndStop(){
JMSListenerContainer listenerContainer=new DummyJMSListener();
ThrottlingCounter counter=new ThrottlingCounter(0,1);
counter.setListenerContainer(listenerContainer);
assertTrue(listenerContainer.isRunning());
counter.incrementAndGet();
assertFalse(listenerContainer.isRunning());
counter.decrementAndGet();
assertTrue(listenerContainer.isRunning());
}
Class: org.apache.cxf.transport.jms.continuations.JMSContinuationProviderTest BooleanVerifier InternalCallVerifier IdentityVerifier HybridVerifier
@Test public void testGetNewContinuation(){
Message m=new MessageImpl();
m.setExchange(new ExchangeImpl());
Counter counter=EasyMock.createMock(Counter.class);
JMSContinuationProvider provider=new JMSContinuationProvider(bus,m,null,counter);
Continuation cw=provider.getContinuation();
assertTrue(cw.isNew());
assertSame(cw,m.get(JMSContinuation.class));
}
InternalCallVerifier IdentityVerifier
@Test public void testGetExistingContinuation(){
Message m=new MessageImpl();
m.setExchange(new ExchangeImpl());
Counter counter=EasyMock.createMock(Counter.class);
JMSContinuation cw=new JMSContinuation(bus,m,null,counter);
m.put(JMSContinuation.class,cw);
JMSContinuationProvider provider=new JMSContinuationProvider(null,m,null,counter);
assertSame(cw,provider.getContinuation());
assertSame(cw,m.get(JMSContinuation.class));
}
InternalCallVerifier NullVerifier
@Test public void testNoContinuationForOneWay(){
Exchange exchange=new ExchangeImpl();
exchange.setOneWay(true);
Message m=new MessageImpl();
m.setExchange(exchange);
Counter counter=EasyMock.createMock(Counter.class);
JMSContinuationProvider provider=new JMSContinuationProvider(null,m,null,counter);
assertNull(provider.getContinuation());
}
Class: org.apache.cxf.transport.jms.continuations.JMSContinuationTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testSuspendResume(){
DummyCounter continuations=new DummyCounter();
JMSContinuation cw=new JMSContinuation(b,m,observer,continuations);
cw.suspend(5000);
Assert.assertEquals(1,continuations.counter.get());
assertFalse(cw.isNew());
assertTrue(cw.isPending());
assertFalse(cw.isResumed());
assertFalse(cw.suspend(1000));
Assert.assertEquals(1,continuations.counter.get());
observer.onMessage(m);
EasyMock.expectLastCall();
EasyMock.replay(observer);
cw.resume();
Assert.assertEquals(0,continuations.counter.get());
assertFalse(cw.isNew());
assertFalse(cw.isPending());
assertTrue(cw.isResumed());
EasyMock.verify(observer);
}
InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testUserObject(){
Counter continuations=new DummyCounter();
JMSContinuation cw=new JMSContinuation(b,m,observer,continuations);
assertNull(cw.getObject());
Object userObject=new Object();
cw.setObject(userObject);
assertSame(userObject,cw.getObject());
}
BooleanVerifier InternalCallVerifier
@Test public void testInitialStatus(){
Counter continuations=EasyMock.createMock(Counter.class);
JMSContinuation cw=new JMSContinuation(b,m,observer,continuations);
assertTrue(cw.isNew());
assertFalse(cw.isPending());
assertFalse(cw.isResumed());
}
BooleanVerifier InternalCallVerifier
@Test public void testSendMessageOnResume(){
Counter continuations=new DummyCounter();
JMSContinuation cw=new JMSContinuation(b,m,observer,continuations);
cw.suspend(5000);
assertFalse(cw.suspend(1000));
observer.onMessage(m);
EasyMock.expectLastCall();
EasyMock.replay(observer);
cw.resume();
EasyMock.verify(observer);
}
Class: org.apache.cxf.transport.jms.uri.JMSEndpointTest InternalCallVerifier EqualityVerifier
@Test public void testRequestUriWithMessageType() throws Exception {
JMSEndpoint endpoint=new JMSEndpoint("jms:queue:Foo.Bar?messageType=text");
assertEquals(JMSEndpoint.QUEUE,endpoint.getJmsVariant());
assertEquals("text",endpoint.getMessageType().value());
endpoint=new JMSEndpoint("jms:queue:Foo.Bar");
assertEquals(JMSEndpoint.QUEUE,endpoint.getJmsVariant());
assertEquals("byte",endpoint.getMessageType().value());
endpoint=new JMSEndpoint("jms:queue:Foo.Bar?messageType=binary");
assertEquals(JMSEndpoint.QUEUE,endpoint.getJmsVariant());
assertEquals("binary",endpoint.getMessageType().value());
}
InternalCallVerifier EqualityVerifier
@Test public void testJNDIWithAdditionalParameters() throws Exception {
JMSEndpoint endpoint=new JMSEndpoint("jms:jndi:Foo.Bar?" + "jndiInitialContextFactory" + "=org.apache.activemq.jndi.ActiveMQInitialContextFactory"+ "&jndiConnectionFactoryName=ConnectionFactory"+ "&jndiURL=tcp://localhost:61616"+ "&jndi-com.sun.jndi.someParameter=someValue"+ "&durableSubscriptionName=dur");
assertEquals(JMSEndpoint.JNDI,endpoint.getJmsVariant());
assertEquals(endpoint.getParameters().size(),0);
assertEquals("org.apache.activemq.jndi.ActiveMQInitialContextFactory",endpoint.getJndiInitialContextFactory());
assertEquals("ConnectionFactory",endpoint.getJndiConnectionFactoryName());
assertEquals("tcp://localhost:61616",endpoint.getJndiURL());
assertEquals("dur",endpoint.getDurableSubscriptionName());
Map addParas=endpoint.getJndiParameters();
assertEquals(1,addParas.size());
assertEquals("someValue",addParas.get("com.sun.jndi.someParameter"));
}
InternalCallVerifier EqualityVerifier
@Test public void testSharedParameters() throws Exception {
JMSEndpoint endpoint=new JMSEndpoint("jms:queue:Foo.Bar?" + "deliveryMode=NON_PERSISTENT" + "&timeToLive=100"+ "&priority=5"+ "&replyToName=foo.bar2");
assertEquals(JMSEndpoint.QUEUE,endpoint.getJmsVariant());
assertEquals(0,endpoint.getParameters().size());
assertEquals(DeliveryModeType.NON_PERSISTENT,endpoint.getDeliveryMode());
assertEquals(100,endpoint.getTimeToLive());
assertEquals(5,endpoint.getPriority());
assertEquals("foo.bar2",endpoint.getReplyToName());
}
InternalCallVerifier EqualityVerifier
@Test public void testJaxWsProps() throws Exception {
EndpointInfo ei=new EndpointInfo();
ei.setProperty(JMSEndpoint.JAXWS_PROPERTY_PREFIX + "durableSubscriptionName",TEST_VALUE);
JMSEndpoint endpoint=new JMSEndpoint(ei,"jms:queue:Foo.Bar");
assertEquals(endpoint.getDurableSubscriptionName(),TEST_VALUE);
}
InternalCallVerifier EqualityVerifier
@Test public void testBasicJNDI() throws Exception {
JMSEndpoint endpoint=new JMSEndpoint("jms:jndi:Foo.Bar");
assertEquals(JMSEndpoint.JNDI,endpoint.getJmsVariant());
assertEquals(endpoint.getDestinationName(),"Foo.Bar");
assertEquals(endpoint.getJmsVariant(),JMSEndpoint.JNDI);
}
InternalCallVerifier EqualityVerifier
@Test public void testTopicParameters() throws Exception {
JMSEndpoint endpoint=new JMSEndpoint("jms:topic:Foo.Bar?foo=bar&foo2=bar2");
assertEquals(JMSEndpoint.TOPIC,endpoint.getJmsVariant());
assertEquals(endpoint.getParameters().size(),2);
assertEquals(endpoint.getParameter("foo"),"bar");
assertEquals(endpoint.getParameter("foo2"),"bar2");
}
InternalCallVerifier EqualityVerifier
@Test public void testQueueParameters() throws Exception {
JMSEndpoint endpoint=new JMSEndpoint("jms:queue:Foo.Bar?foo=bar&foo2=bar2&useConduitIdSelector=false");
assertEquals(JMSEndpoint.QUEUE,endpoint.getJmsVariant());
assertEquals(endpoint.getDestinationName(),"Foo.Bar");
assertEquals(endpoint.getJmsVariant(),JMSEndpoint.QUEUE);
assertEquals(false,endpoint.isUseConduitIdSelector());
assertEquals(endpoint.getParameters().size(),2);
assertEquals(endpoint.getParameter("foo"),"bar");
assertEquals(endpoint.getParameter("foo2"),"bar2");
}
InternalCallVerifier EqualityVerifier
@Test public void testJNDIParameters() throws Exception {
JMSEndpoint endpoint=new JMSEndpoint("jms:jndi:Foo.Bar?" + "jndiInitialContextFactory" + "=org.apache.activemq.jndi.ActiveMQInitialContextFactory"+ "&jndiConnectionFactoryName=ConnectionFactory"+ "&jndiURL=tcp://localhost:61616");
assertEquals(JMSEndpoint.JNDI,endpoint.getJmsVariant());
assertEquals(endpoint.getParameters().size(),0);
assertEquals(endpoint.getDestinationName(),"Foo.Bar");
assertEquals(endpoint.getJndiInitialContextFactory(),"org.apache.activemq.jndi.ActiveMQInitialContextFactory");
assertEquals(endpoint.getJndiConnectionFactoryName(),"ConnectionFactory");
assertEquals(endpoint.getJndiURL(),"tcp://localhost:61616");
}
UtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testReplyToNameParameters() throws Exception {
JMSEndpoint endpoint=new JMSEndpoint("jms:queue:Foo.Bar?replyToName=FOO.Tar");
assertEquals(JMSEndpoint.QUEUE,endpoint.getJmsVariant());
assertEquals("Foo.Bar",endpoint.getDestinationName());
assertNull(endpoint.getTopicReplyToName());
assertEquals("FOO.Tar",endpoint.getReplyToName());
try {
new JMSEndpoint("jms:queue:Foo.Bar?replyToName=FOO.Tar&topicReplyToName=FOO.Zar");
fail("Expecting exception here");
}
catch ( IllegalArgumentException ex) {
}
endpoint=new JMSEndpoint("jms:queue:Foo.Bar?topicReplyToName=FOO.Zar");
assertEquals("Foo.Bar",endpoint.getDestinationName());
assertNull(endpoint.getReplyToName());
assertEquals("FOO.Zar",endpoint.getTopicReplyToName());
}
InternalCallVerifier EqualityVerifier
@Test public void testBasicTopic() throws Exception {
JMSEndpoint endpoint=new JMSEndpoint("jms:topic:Foo.Bar");
assertEquals(JMSEndpoint.TOPIC,endpoint.getJmsVariant());
assertEquals(endpoint.getDestinationName(),"Foo.Bar");
assertEquals(endpoint.getJmsVariant(),JMSEndpoint.TOPIC);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testRequestUri() throws Exception {
JMSEndpoint endpoint=new JMSEndpoint("jms:jndi:Foo.Bar" + "?jndiInitialContextFactory=org.apache.activemq.jndi.ActiveMQInitialContextFactory" + "&targetService=greetMe"+ "&replyToName=replyQueue"+ "&timeToLive=1000"+ "&priority=3"+ "&foo=bar"+ "&foo2=bar2");
assertEquals(JMSEndpoint.JNDI,endpoint.getJmsVariant());
assertEquals(2,endpoint.getParameters().size());
String requestUri=endpoint.getRequestURI();
assertTrue(requestUri.startsWith("jms:jndi:Foo.Bar?"));
assertTrue(requestUri.contains("foo=bar"));
assertTrue(requestUri.contains("foo2=bar2"));
assertFalse(requestUri.contains("jndiInitialContextFactory"));
assertFalse(requestUri.contains("targetService"));
assertFalse(requestUri.contains("replyToName"));
assertFalse(requestUri.contains("priority=3"));
}
InternalCallVerifier EqualityVerifier
@Test public void testBasicQueue() throws Exception {
JMSEndpoint endpoint=new JMSEndpoint("jms:queue:Foo.Bar?concurrentConsumers=21");
assertEquals(JMSEndpoint.QUEUE,endpoint.getJmsVariant());
assertEquals("Foo.Bar",endpoint.getDestinationName());
assertEquals(JMSEndpoint.QUEUE,endpoint.getJmsVariant());
assertEquals(21,endpoint.getConcurrentConsumers());
}
Class: org.apache.cxf.transport.jms.util.JMSUtilTest APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testJMSMessageMarshal() throws IOException, JMSException {
String testMsg="Test Message";
final byte[] testBytes=testMsg.getBytes(Charset.defaultCharset().name());
JMSConfiguration jmsConfig=new JMSConfiguration();
jmsConfig.setConnectionFactory(new ActiveMQConnectionFactory("vm://tesstMarshal?broker.persistent=false"));
try (ResourceCloser closer=new ResourceCloser()){
Connection connection=JMSFactory.createConnection(jmsConfig);
Session session=connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
javax.jms.Message jmsMessage=JMSUtil.createAndSetPayload(testBytes,session,JMSConstants.BYTE_MESSAGE_TYPE);
assertTrue("Message should have been of type BytesMessage ",jmsMessage instanceof BytesMessage);
}
}
Class: org.apache.cxf.transport.local.LocalDestinationTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
/**
* Tests if the status code is available after closing the destination so that it can be logged.
* Note that this test verifies the current approach of setting the status code if it is not set earlier.
* @throws Exception
*/
@Test public void testStatusCodeSetAfterClose() throws Exception {
Bus bus=BusFactory.getDefaultBus();
LocalTransportFactory factory=new LocalTransportFactory();
EndpointInfo ei=new EndpointInfo(null,"http://schemas.xmlsoap.org/soap/http");
ei.setAddress("http://localhost/test");
LocalDestination d=(LocalDestination)factory.getDestination(ei,bus);
MessageImpl m=new MessageImpl();
Conduit conduit=factory.getConduit(ei,bus);
m.put(LocalConduit.IN_CONDUIT,conduit);
Exchange ex=new ExchangeImpl();
ex.put(Bus.class,bus);
m.setExchange(ex);
Integer code=(Integer)m.get(Message.RESPONSE_CODE);
assertNull(code);
Conduit backChannel=d.getBackChannel(m);
backChannel.close(m);
code=(Integer)m.get(Message.RESPONSE_CODE);
assertNotNull(code);
assertEquals(200,code.intValue());
}
Class: org.apache.cxf.transport.servlet.ServletControllerTest BooleanVerifier InternalCallVerifier
@Test public void testGenerateServiceListing() throws Exception {
setReq(null,"/services",null,"true");
expectServiceListGeneratorCalled();
EasyMock.replay(req,registry,serviceListGenerator);
TestServletController sc=new TestServletController(registry,serviceListGenerator);
sc.invoke(req,res);
assertFalse(sc.invokeDestinationCalled());
}
BooleanVerifier InternalCallVerifier
@Test public void testGenerateUnformattedServiceListing() throws Exception {
req.getPathInfo();
EasyMock.expectLastCall().andReturn(null).anyTimes();
req.getContextPath();
EasyMock.expectLastCall().andReturn("");
req.getServletPath();
EasyMock.expectLastCall().andReturn("");
req.getRequestURI();
EasyMock.expectLastCall().andReturn("/services").times(2);
req.getParameter("stylesheet");
EasyMock.expectLastCall().andReturn(null);
req.getParameter("formatted");
EasyMock.expectLastCall().andReturn("false");
req.getRequestURL();
EasyMock.expectLastCall().andReturn(new StringBuffer("http://localhost:8080/services"));
req.setAttribute(Message.BASE_PATH,"http://localhost:8080");
EasyMock.expectLastCall().anyTimes();
registry.getDestinationsPaths();
EasyMock.expectLastCall().andReturn(Collections.emptySet()).atLeastOnce();
registry.getDestinationForPath("",true);
EasyMock.expectLastCall().andReturn(null).anyTimes();
expectServiceListGeneratorCalled();
EasyMock.replay(req,registry,serviceListGenerator);
TestServletController sc=new TestServletController(registry,serviceListGenerator);
sc.invoke(req,res);
assertFalse(sc.invokeDestinationCalled());
}
BooleanVerifier InternalCallVerifier
@Test public void testHideServiceListing() throws Exception {
req.getPathInfo();
EasyMock.expectLastCall().andReturn(null);
registry.getDestinationForPath("",true);
EasyMock.expectLastCall().andReturn(null).atLeastOnce();
AbstractHTTPDestination dest=EasyMock.createMock(AbstractHTTPDestination.class);
registry.checkRestfulRequest("");
EasyMock.expectLastCall().andReturn(dest).atLeastOnce();
dest.getBus();
EasyMock.expectLastCall().andReturn(null).anyTimes();
dest.getMessageObserver();
EasyMock.expectLastCall().andReturn(EasyMock.createMock(MessageObserver.class)).atLeastOnce();
expectServiceListGeneratorNotCalled();
EasyMock.replay(req,registry,serviceListGenerator,dest);
TestServletController sc=new TestServletController(registry,serviceListGenerator);
sc.setHideServiceList(true);
sc.invoke(req,res);
assertTrue(sc.invokeDestinationCalled());
}
BooleanVerifier InternalCallVerifier
@Test public void testDifferentServiceListPath() throws Exception {
setReq(null,"/listing",null,"true");
expectServiceListGeneratorCalled();
EasyMock.replay(req,registry,serviceListGenerator);
TestServletController sc=new TestServletController(registry,serviceListGenerator);
sc.setServiceListRelativePath("/listing");
sc.invoke(req,res);
assertFalse(sc.invokeDestinationCalled());
}
Class: org.apache.cxf.transport.udp.UDPTransportTest InternalCallVerifier EqualityVerifier
@Test public void testBroadcastUDP() throws Exception {
if (System.getProperties().getProperty("os.name").equals("Linux") && System.getProperties().getProperty("os.version").indexOf("el") > 0) {
System.out.println("Skipping broadcast test for REL");
return;
}
Enumeration interfaces=NetworkInterface.getNetworkInterfaces();
int count=0;
while (interfaces.hasMoreElements()) {
NetworkInterface networkInterface=interfaces.nextElement();
if (!networkInterface.isUp() || networkInterface.isLoopback()) {
continue;
}
count++;
}
if (count == 0) {
System.out.println("Skipping broadcast test");
return;
}
JaxWsProxyFactoryBean fact=new JaxWsProxyFactoryBean();
fact.setAddress("udp://:" + PORT + "/foo");
Greeter g=fact.create(Greeter.class);
assertEquals("Hello World",g.greetMe("World"));
((java.io.Closeable)g).close();
}
IterativeVerifier InternalCallVerifier EqualityVerifier
@Test public void testSimpleUDP() throws Exception {
JaxWsProxyFactoryBean fact=new JaxWsProxyFactoryBean();
fact.setAddress("udp://localhost:" + PORT);
Greeter g=fact.create(Greeter.class);
for (int x=0; x < 5; x++) {
assertEquals("Hello World",g.greetMe("World"));
}
((java.io.Closeable)g).close();
}
InternalCallVerifier EqualityVerifier
@Test public void testLargeRequest() throws Exception {
JaxWsProxyFactoryBean fact=new JaxWsProxyFactoryBean();
fact.setAddress("udp://localhost:" + PORT);
Greeter g=fact.create(Greeter.class);
StringBuilder b=new StringBuilder(100000);
for (int x=0; x < 6500; x++) {
b.append("Hello ");
}
assertEquals("Hello " + b.toString(),g.greetMe(b.toString()));
((java.io.Closeable)g).close();
}
Class: org.apache.cxf.transport.websocket.WebSocketTransportFactoryTest InternalCallVerifier NullVerifier
@Test public void testGetDestination() throws Exception {
Bus bus=BusFactory.getDefaultBus();
EndpointInfo ei=new EndpointInfo();
ei.setAddress("ws://localhost:8888/bar/foo");
WebSocketTransportFactory factory=bus.getExtension(WebSocketTransportFactory.class);
assertNotNull(factory);
Destination dest=factory.getDestination(ei,bus);
assertNotNull(dest);
}
Class: org.apache.cxf.transport.websocket.ahc.AhcWebSocketConduitTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testResponseParsing() throws Exception {
AhcWebSocketConduit.Response resp=new AhcWebSocketConduit.Response(WebSocketConstants.DEFAULT_RESPONSE_ID_KEY,TEST_RESPONSE1);
assertEquals(200,resp.getStatusCode());
assertEquals("59610eed-d9de-4692-96d4-bb95a36c41ea",resp.getId());
assertEquals("text/plain",resp.getContentType());
assertTrue(resp.getEntity() instanceof String);
assertEquals("Hola!",resp.getEntity());
resp=new AhcWebSocketConduit.Response(WebSocketConstants.DEFAULT_RESPONSE_ID_KEY,TEST_RESPONSE1.getBytes());
assertEquals(200,resp.getStatusCode());
assertEquals("59610eed-d9de-4692-96d4-bb95a36c41ea",resp.getId());
assertEquals("text/plain",resp.getContentType());
assertTrue(resp.getEntity() instanceof byte[]);
assertEquals("Hola!",resp.getTextEntity());
resp=new AhcWebSocketConduit.Response(WebSocketConstants.DEFAULT_RESPONSE_ID_KEY,TEST_RESPONSE2);
assertEquals(0,resp.getStatusCode());
assertEquals("59610eed-d9de-4692-96d4-bb95a36c41ea",resp.getId());
assertNull(resp.getContentType());
assertTrue(resp.getEntity() instanceof String);
assertEquals("Nada!",resp.getEntity());
resp=new AhcWebSocketConduit.Response(WebSocketConstants.DEFAULT_RESPONSE_ID_KEY,TEST_RESPONSE2.getBytes());
assertEquals(0,resp.getStatusCode());
assertEquals("59610eed-d9de-4692-96d4-bb95a36c41ea",resp.getId());
assertNull(resp.getContentType());
assertTrue(resp.getEntity() instanceof byte[]);
assertEquals("Nada!",resp.getTextEntity());
}
Class: org.apache.cxf.transport.websocket.atmosphere.AtmosphereWebSocketServletDestinationTest InternalCallVerifier NullVerifier
@Test public void testRegisteration() throws Exception {
Bus bus=new ExtensionManagerBus();
DestinationRegistry registry=new HTTPTransportFactory().getRegistry();
EndpointInfo endpoint=new EndpointInfo();
endpoint.setAddress(ENDPOINT_ADDRESS);
endpoint.setName(ENDPOINT_NAME);
TestAtmosphereWebSocketServletDestination dest=new TestAtmosphereWebSocketServletDestination(bus,registry,endpoint,ENDPOINT_ADDRESS);
dest.activate();
assertNotNull(registry.getDestinationForPath(ENDPOINT_ADDRESS));
dest.deactivate();
assertNull(registry.getDestinationForPath(ENDPOINT_ADDRESS));
}
Class: org.apache.cxf.transport.websocket.jetty.JettyWebSocketDestinationTest InternalCallVerifier NullVerifier
@Test public void testRegisteration() throws Exception {
Bus bus=new ExtensionManagerBus();
DestinationRegistry registry=new HTTPTransportFactory().getRegistry();
EndpointInfo endpoint=new EndpointInfo();
endpoint.setAddress(ENDPOINT_ADDRESS);
endpoint.setName(ENDPOINT_NAME);
JettyHTTPServerEngine engine=EasyMock.createMock(JettyHTTPServerEngine.class);
control.replay();
TestJettyWebSocketDestination dest=new TestJettyWebSocketDestination(bus,registry,endpoint,null,engine);
dest.activate();
assertNotNull(registry.getDestinationForPath(ENDPOINT_ADDRESS));
dest.deactivate();
assertNull(registry.getDestinationForPath(ENDPOINT_ADDRESS));
}
Class: org.apache.cxf.workqueue.AutomaticWorkQueueTest BooleanVerifier InternalCallVerifier
@Test public void testThreadPoolShrinkUnbounded() throws Exception {
workqueue=new AutomaticWorkQueueImpl(UNBOUNDED_MAX_QUEUE_SIZE,INITIAL_SIZE,UNBOUNDED_HIGH_WATER_MARK,DEFAULT_LOW_WATER_MARK,100L);
DeadLockThread dead=new DeadLockThread(workqueue,1000,5L);
checkDeadLock(dead);
int i=0;
int last=workqueue.getPoolSize();
while (workqueue.getPoolSize() > DEFAULT_LOW_WATER_MARK && i++ < 50) {
if (last != workqueue.getPoolSize()) {
last=workqueue.getPoolSize();
i=0;
}
Thread.sleep(100);
}
int sz=workqueue.getPoolSize();
assertTrue("threads_total(): " + sz,workqueue.getPoolSize() <= DEFAULT_LOW_WATER_MARK);
}
IterativeVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier IgnoredMethod HybridVerifier
@Test @Ignore("The test is failed on openjdk") public void testEnqueueImmediate(){
workqueue=new AutomaticWorkQueueImpl(DEFAULT_MAX_QUEUE_SIZE,INITIAL_SIZE,DEFAULT_HIGH_WATER_MARK,DEFAULT_LOW_WATER_MARK,DEFAULT_DEQUEUE_TIMEOUT);
try {
Thread.sleep(100);
}
catch ( Exception e) {
}
assertEquals(0,workqueue.getSize());
assertEquals(0,workqueue.getPoolSize());
assertEquals(0,workqueue.getActiveCount());
BlockingWorkItem[] workItems=new BlockingWorkItem[DEFAULT_HIGH_WATER_MARK];
BlockingWorkItem[] fillers=new BlockingWorkItem[DEFAULT_MAX_QUEUE_SIZE];
try {
for (int i=0; i < DEFAULT_HIGH_WATER_MARK; i++) {
workItems[i]=new BlockingWorkItem();
try {
workqueue.execute(workItems[i]);
}
catch ( RejectedExecutionException ex) {
fail("failed on item[" + i + "] with: "+ ex);
}
}
while (workqueue.getActiveCount() < DEFAULT_HIGH_WATER_MARK) {
try {
Thread.sleep(250);
}
catch ( InterruptedException ex) {
}
}
for (int i=0; i < DEFAULT_MAX_QUEUE_SIZE; i++) {
fillers[i]=new BlockingWorkItem();
try {
workqueue.execute(fillers[i]);
}
catch ( RejectedExecutionException ex) {
fail("failed on filler[" + i + "] with: "+ ex);
}
}
try {
Thread.sleep(250);
}
catch ( InterruptedException ex) {
}
assertTrue(workqueue.toString(),workqueue.isFull());
assertEquals(workqueue.toString(),DEFAULT_HIGH_WATER_MARK,workqueue.getPoolSize());
assertEquals(workqueue.toString(),DEFAULT_HIGH_WATER_MARK,workqueue.getActiveCount());
try {
workqueue.execute(new BlockingWorkItem());
fail("workitem should not have been accepted.");
}
catch ( RejectedExecutionException ex) {
}
workItems[0].unblock();
boolean accepted=false;
workItems[0]=new BlockingWorkItem();
for (int i=0; i < 20 && !accepted; i++) {
try {
Thread.sleep(100);
}
catch ( InterruptedException ex) {
}
try {
workqueue.execute(workItems[0]);
accepted=true;
}
catch ( RejectedExecutionException ex) {
}
}
assertTrue(accepted);
}
finally {
for (int i=0; i < DEFAULT_HIGH_WATER_MARK; i++) {
if (workItems[i] != null) {
workItems[i].unblock();
}
}
for (int i=0; i < DEFAULT_MAX_QUEUE_SIZE; i++) {
if (fillers[i] != null) {
fillers[i].unblock();
}
}
}
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testConstructor(){
workqueue=new AutomaticWorkQueueImpl(DEFAULT_MAX_QUEUE_SIZE,INITIAL_SIZE,DEFAULT_HIGH_WATER_MARK,DEFAULT_LOW_WATER_MARK,DEFAULT_DEQUEUE_TIMEOUT);
assertNotNull(workqueue);
assertEquals(DEFAULT_MAX_QUEUE_SIZE,workqueue.getMaxSize());
assertEquals(DEFAULT_HIGH_WATER_MARK,workqueue.getHighWaterMark());
assertEquals(DEFAULT_LOW_WATER_MARK,workqueue.getLowWaterMark());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testUnboundedConstructor(){
workqueue=new AutomaticWorkQueueImpl(UNBOUNDED_MAX_QUEUE_SIZE,INITIAL_SIZE,UNBOUNDED_HIGH_WATER_MARK,UNBOUNDED_LOW_WATER_MARK,DEFAULT_DEQUEUE_TIMEOUT);
assertNotNull(workqueue);
assertEquals(AutomaticWorkQueueImpl.DEFAULT_MAX_QUEUE_SIZE,workqueue.getMaxSize());
assertEquals(UNBOUNDED_HIGH_WATER_MARK,workqueue.getHighWaterMark());
assertEquals(UNBOUNDED_LOW_WATER_MARK,workqueue.getLowWaterMark());
}
InternalCallVerifier EqualityVerifier
@Test public void testShutdown(){
workqueue=new AutomaticWorkQueueImpl(DEFAULT_MAX_QUEUE_SIZE,INITIAL_SIZE,INITIAL_SIZE,INITIAL_SIZE,500);
assertEquals(0,workqueue.getSize());
DeadLockThread dead=new DeadLockThread(workqueue,10,5L);
dead.start();
checkCompleted(dead);
workqueue.shutdown(true);
for (int i=0; i < 20 && (workqueue.getSize() > 0 || workqueue.getPoolSize() > 0); i++) {
try {
Thread.sleep(250);
}
catch ( InterruptedException ie) {
}
}
assertEquals(0,workqueue.getSize());
assertEquals(0,workqueue.getPoolSize());
workqueue=null;
}
BooleanVerifier InternalCallVerifier
@Test public void testThreadPoolShrink(){
workqueue=new AutomaticWorkQueueImpl(UNBOUNDED_MAX_QUEUE_SIZE,20,20,10,100L);
DeadLockThread dead=new DeadLockThread(workqueue,1000,5L);
checkDeadLock(dead);
int i=0;
while (workqueue.getPoolSize() > 10 && i++ < 50) {
try {
Thread.sleep(100);
}
catch ( InterruptedException ie) {
}
}
assertTrue(workqueue.getLowWaterMark() >= workqueue.getPoolSize());
}
InternalCallVerifier EqualityVerifier
@Test public void testEnqueue(){
workqueue=new AutomaticWorkQueueImpl(DEFAULT_MAX_QUEUE_SIZE,INITIAL_SIZE,DEFAULT_HIGH_WATER_MARK,DEFAULT_LOW_WATER_MARK,DEFAULT_DEQUEUE_TIMEOUT);
try {
Thread.sleep(100);
}
catch ( Exception e) {
}
assertEquals(0,workqueue.getSize());
assertEquals(0,workqueue.getPoolSize());
assertEquals(0,workqueue.getActiveCount());
workqueue.execute(new TestWorkItem(),TIMEOUT);
int i=0;
while (workqueue.getSize() != 0 && i++ < 50) {
try {
Thread.sleep(100);
}
catch ( InterruptedException ie) {
}
}
assertEquals(0,workqueue.getSize());
}
Class: org.apache.cxf.ws.addressing.impl.ContextUtilsTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetActionFromExtensible(){
Map attributes=new HashMap();
Extensible ext=control.createMock(Extensible.class);
EasyMock.expect(ext.getExtensionAttributes()).andReturn(attributes).anyTimes();
attributes.put(WSA_ACTION_QNAME,"urn:foo:test:2");
EasyMock.expect(ext.getExtensionAttribute(JAXWSAConstants.WSAW_ACTION_QNAME)).andReturn("urn:foo:test:1");
control.replay();
String action=InternalContextUtils.getAction(ext);
assertEquals("urn:foo:test:1",action);
control.reset();
attributes.clear();
EasyMock.expect(ext.getExtensionAttributes()).andReturn(attributes).anyTimes();
EasyMock.expect(ext.getExtensionAttribute(JAXWSAConstants.WSAW_ACTION_QNAME)).andReturn(null);
attributes.put(WSA_ACTION_QNAME,"urn:foo:test:2");
control.replay();
action=InternalContextUtils.getAction(ext);
assertEquals("urn:foo:test:2",action);
control.reset();
attributes.clear();
EasyMock.expect(ext.getExtensionAttributes()).andReturn(attributes).anyTimes();
EasyMock.expect(ext.getExtensionAttribute(JAXWSAConstants.WSAW_ACTION_QNAME)).andReturn(null);
attributes.put(OLD_WSDL_WSA_ACTION_QNAME,"urn:foo:test:3");
control.replay();
action=InternalContextUtils.getAction(ext);
assertEquals("urn:foo:test:3",action);
control.reset();
attributes.clear();
EasyMock.expect(ext.getExtensionAttributes()).andReturn(attributes).anyTimes();
EasyMock.expect(ext.getExtensionAttribute(JAXWSAConstants.WSAW_ACTION_QNAME)).andReturn(null);
control.replay();
action=InternalContextUtils.getAction(ext);
assertEquals(null,action);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetActionFromMessage(){
Message msg=control.createMock(Message.class);
Exchange exchange=control.createMock(Exchange.class);
QName mqname=new QName("http://foo.com","bar");
QName fqname=new QName("urn:foo:test:4","fault");
OperationInfo operationInfo=new OperationInfo();
MessageInfo messageInfo=new MessageInfo(operationInfo,Type.OUTPUT,mqname);
messageInfo.addMessagePart(new MessagePartInfo(new QName("http://foo.com","partInfo"),null));
operationInfo.setOutput("outputName",messageInfo);
FaultInfo faultInfo=new FaultInfo(fqname,mqname,operationInfo);
operationInfo.addFault(faultInfo);
BindingOperationInfo boi=new BindingOperationInfo(null,operationInfo);
EasyMock.expect(msg.getExchange()).andReturn(exchange).anyTimes();
EasyMock.expect(exchange.getBindingOperationInfo()).andReturn(boi);
EasyMock.expect(msg.get(ContextUtils.ACTION)).andReturn("urn:foo:test:1");
control.replay();
AttributedURIType action=InternalContextUtils.getAction(msg);
assertNotNull(action);
assertEquals("urn:foo:test:1",action.getValue());
control.reset();
EasyMock.expect(msg.getExchange()).andReturn(exchange).anyTimes();
EasyMock.expect(exchange.getBindingOperationInfo()).andReturn(boi);
EasyMock.expect(msg.get(SoapBindingConstants.SOAP_ACTION)).andReturn("urn:foo:test:2");
control.replay();
action=InternalContextUtils.getAction(msg);
assertNotNull(action);
assertEquals("urn:foo:test:2",action.getValue());
control.reset();
EasyMock.expect(msg.getExchange()).andReturn(exchange).anyTimes();
EasyMock.expect(exchange.getBindingOperationInfo()).andReturn(boi);
messageInfo.setProperty(ContextUtils.ACTION,"urn:foo:test:3");
control.replay();
action=InternalContextUtils.getAction(msg);
assertNotNull(action);
assertEquals("urn:foo:test:3",action.getValue());
control.reset();
SoapFault fault=new SoapFault("faulty service",new RuntimeException(),fqname);
EasyMock.expect(msg.getExchange()).andReturn(exchange).anyTimes();
EasyMock.expect(msg.getContent(Exception.class)).andReturn(fault).anyTimes();
EasyMock.expect(exchange.getBindingOperationInfo()).andReturn(boi);
control.replay();
action=InternalContextUtils.getAction(msg);
assertNull(action);
control.reset();
faultInfo.addMessagePart(new MessagePartInfo(new QName("http://foo.com","faultInfo"),null));
faultInfo.getMessagePart(0).setTypeClass(RuntimeException.class);
faultInfo.addExtensionAttribute(Names.WSAW_ACTION_QNAME,"urn:foo:test:4");
EasyMock.expect(msg.getExchange()).andReturn(exchange).anyTimes();
EasyMock.expect(msg.getContent(Exception.class)).andReturn(fault).anyTimes();
EasyMock.expect(exchange.getBindingOperationInfo()).andReturn(boi);
control.replay();
action=InternalContextUtils.getAction(msg);
assertNotNull(action);
assertEquals("urn:foo:test:4",action.getValue());
control.reset();
fault=new SoapFault("Action Mismatch",new QName(Names.WSA_NAMESPACE_NAME,Names.ACTION_MISMATCH_NAME));
EasyMock.expect(msg.getExchange()).andReturn(exchange).anyTimes();
EasyMock.expect(msg.getContent(Exception.class)).andReturn(fault).anyTimes();
EasyMock.expect(exchange.getBindingOperationInfo()).andReturn(boi);
control.replay();
action=InternalContextUtils.getAction(msg);
assertNotNull(action);
assertEquals(Names.WSA_DEFAULT_FAULT_ACTION,action.getValue());
control.reset();
fault=new SoapFault("faulty service",new TestFault(),Fault.FAULT_CODE_SERVER);
faultInfo.addMessagePart(new MessagePartInfo(new QName("http://foo.com:7","faultInfo"),null));
faultInfo.getMessagePart(0).setTypeClass(Object.class);
faultInfo.getMessagePart(0).setConcreteName(new QName("urn:foo:test:7","testFault"));
faultInfo.addExtensionAttribute(Names.WSAW_ACTION_QNAME,"urn:foo:test:7");
EasyMock.expect(msg.getExchange()).andReturn(exchange).anyTimes();
EasyMock.expect(msg.getContent(Exception.class)).andReturn(fault).anyTimes();
EasyMock.expect(exchange.getBindingOperationInfo()).andReturn(boi);
control.replay();
action=InternalContextUtils.getAction(msg);
assertNotNull(action);
assertEquals("urn:foo:test:7",action.getValue());
}
Class: org.apache.cxf.ws.addressing.impl.MAPAggregatorTest InternalCallVerifier IdentityVerifier
@Test public void testReplyToWithAnonymousAddressRetained() throws Exception {
Message message=new MessageImpl();
Exchange exchange=new ExchangeImpl();
message.setExchange(exchange);
exchange.setOutMessage(message);
setUpMessageProperty(message,REQUESTOR_ROLE,Boolean.TRUE);
AddressingProperties maps=new AddressingProperties();
EndpointReferenceType replyTo=new EndpointReferenceType();
replyTo.setAddress(ContextUtils.getAttributedURI(Names.WSA_ANONYMOUS_ADDRESS));
maps.setReplyTo(replyTo);
AttributedURIType id=ContextUtils.getAttributedURI("urn:uuid:12345");
maps.setMessageID(id);
maps.setAction(ContextUtils.getAttributedURI(""));
setUpMessageProperty(message,CLIENT_ADDRESSING_PROPERTIES,maps);
aggregator.mediate(message,false);
AddressingProperties props=(AddressingProperties)message.get(JAXWSAConstants.ADDRESSING_PROPERTIES_OUTBOUND);
assertSame(replyTo,props.getReplyTo());
}
InternalCallVerifier EqualityVerifier
@Test public void testGetActionUriForNormalOp() throws Exception {
Message message=setUpMessage(true,true,false,true,true);
String action=aggregator.getActionUri(message,false);
control.verify();
assertEquals("http://foo/bar/SEI/opRequest",action);
}
InternalCallVerifier EqualityVerifier
@Test public void testGetReplyToUsingBaseAddress() throws Exception {
Message message=new MessageImpl();
Exchange exchange=new ExchangeImpl();
message.setExchange(exchange);
final String localReplyTo="/SoapContext/decoupled";
final String decoupledEndpointBase="http://localhost:8181/cxf";
final String replyTo=decoupledEndpointBase + localReplyTo;
ServiceInfo s=new ServiceInfo();
Service svc=new ServiceImpl(s);
EndpointInfo ei=new EndpointInfo();
InterfaceInfo ii=s.createInterface(new QName("FooInterface"));
s.setInterface(ii);
ii.addOperation(new QName("fooOp"));
SoapBindingInfo b=new SoapBindingInfo(s,"http://schemas.xmlsoap.org/soap/",Soap11.getInstance());
b.setTransportURI("http://schemas.xmlsoap.org/soap/http");
ei.setBinding(b);
ei.setAddress("http://nowhere.com/bar/foo");
ei.setName(new QName("http://nowhere.com/port","foo"));
Bus bus=new ExtensionManagerBus();
DestinationFactoryManager dfm=control.createMock(DestinationFactoryManager.class);
DestinationFactory df=control.createMock(DestinationFactory.class);
Destination d=control.createMock(Destination.class);
bus.setExtension(dfm,DestinationFactoryManager.class);
EasyMock.expect(dfm.getDestinationFactoryForUri(localReplyTo)).andReturn(df);
EasyMock.expect(df.getDestination(EasyMock.anyObject(EndpointInfo.class),EasyMock.anyObject(Bus.class))).andReturn(d);
EasyMock.expect(d.getAddress()).andReturn(EndpointReferenceUtils.getEndpointReference(localReplyTo));
Endpoint ep=new EndpointImpl(bus,svc,ei);
exchange.put(Endpoint.class,ep);
exchange.put(Bus.class,bus);
exchange.setOutMessage(message);
setUpMessageProperty(message,REQUESTOR_ROLE,Boolean.TRUE);
message.getContextualProperty(WSAContextUtils.REPLYTO_PROPERTY);
message.put(WSAContextUtils.REPLYTO_PROPERTY,localReplyTo);
message.put(WSAContextUtils.DECOUPLED_ENDPOINT_BASE_PROPERTY,decoupledEndpointBase);
AddressingProperties maps=new AddressingProperties();
AttributedURIType id=ContextUtils.getAttributedURI("urn:uuid:12345");
maps.setMessageID(id);
maps.setAction(ContextUtils.getAttributedURI(""));
setUpMessageProperty(message,CLIENT_ADDRESSING_PROPERTIES,maps);
control.replay();
aggregator.mediate(message,false);
AddressingProperties props=(AddressingProperties)message.get(JAXWSAConstants.ADDRESSING_PROPERTIES_OUTBOUND);
assertEquals(replyTo,props.getReplyTo().getAddress().getValue());
control.verify();
}
Class: org.apache.cxf.ws.addressing.soap.DecoupledFaultHandlerTest BooleanVerifier InternalCallVerifier IdentityVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testOnewayFault(){
DecoupledFaultHandler handler=new DecoupledFaultHandler(){
protected Destination createDecoupledDestination( Exchange exchange, EndpointReferenceType epr){
assertEquals("http://bar",epr.getAddress().getValue());
return EasyMock.createMock(Destination.class);
}
}
;
SoapMessage message=new SoapMessage(new MessageImpl());
QName qname=new QName("http://cxf.apache.org/mustunderstand","TestMU");
message.getHeaders().add(new Header(qname,new Object()));
AddressingProperties maps=new AddressingProperties();
EndpointReferenceType faultTo=new EndpointReferenceType();
faultTo.setAddress(new AttributedURIType());
faultTo.getAddress().setValue("http://bar");
maps.setFaultTo(faultTo);
message.put(ContextUtils.getMAPProperty(false,false,false),maps);
Exchange exchange=new ExchangeImpl();
message.setExchange(exchange);
exchange.setInMessage(message);
exchange.setOneWay(true);
handler.handleFault(message);
assertTrue(message.getHeaders().isEmpty());
assertFalse(exchange.isOneWay());
assertSame(message,exchange.getOutMessage());
assertNotNull(exchange.getDestination());
}
Class: org.apache.cxf.ws.addressing.soap.MAPCodecTest BooleanVerifier InternalCallVerifier
@Test public void testGetHeaders() throws Exception {
Set headers=codec.getUnderstoodHeaders();
assertTrue("expected From header",headers.contains(Names.WSA_FROM_QNAME));
assertTrue("expected To header",headers.contains(Names.WSA_TO_QNAME));
assertTrue("expected ReplyTo header",headers.contains(Names.WSA_REPLYTO_QNAME));
assertTrue("expected FaultTo header",headers.contains(Names.WSA_FAULTTO_QNAME));
assertTrue("expected Action header",headers.contains(Names.WSA_ACTION_QNAME));
assertTrue("expected MessageID header",headers.contains(Names.WSA_MESSAGEID_QNAME));
}
Class: org.apache.cxf.ws.discovery.WSDiscoveryClientTest InternalCallVerifier EqualityVerifier
@Test public void testMultiResponses() throws Exception {
if (System.getProperties().getProperty("os.name").equals("Linux") && System.getProperties().getProperty("os.version").indexOf("el") > 0) {
System.out.println("Skipping MultiResponse test for REL");
return;
}
Enumeration interfaces=NetworkInterface.getNetworkInterfaces();
int count=0;
while (interfaces.hasMoreElements()) {
NetworkInterface networkInterface=interfaces.nextElement();
if (!networkInterface.isUp() || networkInterface.isLoopback()) {
continue;
}
count++;
}
if (count == 0) {
System.out.println("Skipping MultiResponse test");
return;
}
new Thread(new Runnable(){
public void run(){
try {
InetAddress address=InetAddress.getByName("239.255.255.250");
MulticastSocket s=new MulticastSocket(Integer.parseInt(PORT));
s.setBroadcast(true);
s.setNetworkInterface(findIpv4Interface());
s.joinGroup(address);
s.setReceiveBufferSize(64 * 1024);
s.setSoTimeout(5000);
byte[] bytes=new byte[64 * 1024];
DatagramPacket p=new DatagramPacket(bytes,bytes.length,address,Integer.parseInt(PORT));
s.receive(p);
SocketAddress sa=p.getSocketAddress();
String incoming=new String(p.getData(),0,p.getLength(),StandardCharsets.UTF_8);
int idx=incoming.indexOf("MessageID");
idx=incoming.indexOf('>',idx);
incoming=incoming.substring(idx + 1);
idx=incoming.indexOf("");
incoming=incoming.substring(0,idx);
for (int x=1; x < 4; x++) {
InputStream ins=WSDiscoveryClientTest.class.getResourceAsStream("msg" + x + ".xml");
String msg=IOUtils.readStringFromStream(ins);
msg=msg.replace("urn:uuid:883d0d53-92aa-4066-9b6f-9eadb1832366",incoming);
byte out[]=msg.getBytes(StandardCharsets.UTF_8);
DatagramPacket outp=new DatagramPacket(out,0,out.length,sa);
s.send(outp);
}
s.close();
}
catch ( Throwable t) {
t.printStackTrace();
}
}
}
).start();
Bus bus=BusFactory.newInstance().createBus();
new LoggingFeature().initialize(bus);
WSDiscoveryClient c=new WSDiscoveryClient(bus);
c.setVersion10();
c.setAddress("soap.udp://239.255.255.250:" + PORT);
ProbeType pt=new ProbeType();
ScopesType scopes=new ScopesType();
pt.setScopes(scopes);
ProbeMatchesType pmts=c.probe(pt,1000);
Assert.assertEquals(2,pmts.getProbeMatch().size());
c.close();
bus.shutdown(true);
}
Class: org.apache.cxf.ws.eventing.integration.SubscriptionGrantingTest APIUtilityVerifier BooleanVerifier InternalCallVerifier
/**
* specification:
* The expiration time MAY be either a specific time or a duration but MUST
* be of the same type as the wse:Expires element of the corresponding request.
* If the corresponding request did not contain a wse:Expires element, this
* element MUST be a duration (xs:duration).
* @throws IOException
*/
@Test public void testExpirationGrantingWithoutBestEffort() throws IOException {
Subscribe subscribe=new Subscribe();
ExpirationType exp=new ExpirationType();
exp.setValue(DurationAndDateUtil.convertToXMLString(DurationAndDateUtil.parseDurationOrTimestamp("PT0S")));
subscribe.setExpires(exp);
DeliveryType delivery=new DeliveryType();
subscribe.setDelivery(delivery);
subscribe.getDelivery().getContent().add(createDummyNotifyTo());
SubscribeResponse resp=eventSourceClient.subscribeOp(subscribe);
Assert.assertTrue("Specification requires that EventSource return a xs:duration " + "expirationType if a xs:duration was requested by client",DurationAndDateUtil.isDuration(resp.getGrantedExpires().getValue()));
subscribe=new Subscribe();
exp=new ExpirationType();
XMLGregorianCalendar dateRequest=(XMLGregorianCalendar)DurationAndDateUtil.parseDurationOrTimestamp("2138-06-26T12:23:12.000-01:00");
exp.setValue(DurationAndDateUtil.convertToXMLString(dateRequest));
subscribe.setExpires(exp);
delivery=new DeliveryType();
subscribe.setDelivery(delivery);
subscribe.getDelivery().getContent().add(createDummyNotifyTo());
resp=eventSourceClient.subscribeOp(subscribe);
Assert.assertTrue("Specification requires that EventSource return a " + "xs:dateTime expirationType if a xs:dateTime was requested by client",DurationAndDateUtil.isXMLGregorianCalendar(resp.getGrantedExpires().getValue()));
XMLGregorianCalendar returned=DurationAndDateUtil.parseXMLGregorianCalendar(resp.getGrantedExpires().getValue());
System.out.println("granted expiration: " + returned.normalize().toXMLFormat());
System.out.println("requested expiration: " + dateRequest.normalize().toXMLFormat());
Assert.assertTrue("Server should have returned exactly the same date as we requested",returned.equals(dateRequest));
subscribe=new Subscribe();
delivery=new DeliveryType();
subscribe.setDelivery(delivery);
subscribe.getDelivery().getContent().add(createDummyNotifyTo());
resp=eventSourceClient.subscribeOp(subscribe);
Assert.assertTrue("Specification requires that EventSource return a xs:duration " + "expirationType if no specific expirationType was requested by client",DurationAndDateUtil.isDuration(resp.getGrantedExpires().getValue()));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
/**
* When BestEffort=true, the server doesn't have to grant exactly the date as we requested
* @throws IOException
*/
@Test public void testExpirationGrantingWithBestEffort() throws IOException {
Subscribe subscribe=new Subscribe();
ExpirationType exp=new ExpirationType();
DeliveryType delivery=new DeliveryType();
XMLGregorianCalendar dateRequest=(XMLGregorianCalendar)DurationAndDateUtil.parseDurationOrTimestamp("2138-06-26T12:23:12.000-01:00");
exp.setValue(DurationAndDateUtil.convertToXMLString(dateRequest));
exp.setBestEffort(true);
subscribe.setExpires(exp);
subscribe.setDelivery(delivery);
subscribe.getDelivery().getContent().add(createDummyNotifyTo());
SubscribeResponse resp=eventSourceClient.subscribeOp(subscribe);
Assert.assertTrue("Specification requires that EventSource return a " + "xs:dateTime expirationType if a xs:dateTime was requested by client",DurationAndDateUtil.isXMLGregorianCalendar(resp.getGrantedExpires().getValue()));
}
Class: org.apache.cxf.ws.eventing.integration.SubscriptionManagementTest APIUtilityVerifier UtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
/**
* Tries to create a subscription, then cancel it, then obtain its status.
* The last mentioned operation should fail.
*/
@Test public void unsubscribeAndThenGetStatus() throws Exception {
Subscribe subscribe=new Subscribe();
ExpirationType exp=new ExpirationType();
exp.setValue(DurationAndDateUtil.convertToXMLString(DurationAndDateUtil.parseDurationOrTimestamp("PT0S")));
subscribe.setExpires(exp);
DeliveryType delivery=new DeliveryType();
subscribe.setDelivery(delivery);
subscribe.getDelivery().getContent().add(createDummyNotifyTo());
SubscribeResponse subscribeResponse=eventSourceClient.subscribeOp(subscribe);
SubscriptionManagerEndpoint client=createSubscriptionManagerClient(subscribeResponse.getSubscriptionManager().getReferenceParameters());
UnsubscribeResponse unsubscribeResponse=client.unsubscribeOp(new Unsubscribe());
Assert.assertNotNull(unsubscribeResponse);
try {
client.getStatusOp(new GetStatus());
}
catch ( javax.xml.ws.soap.SOAPFaultException ex) {
Assert.assertTrue(ex.getFault().getFaultCode().contains(UnknownSubscription.LOCAL_PART));
Assert.assertTrue(ex.getFault().getTextContent().contains(UnknownSubscription.REASON));
return;
}
Assert.fail("The subscription manager should have refused to send status of a cancelled subscription");
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
/**
* Tests the Renew operation, while specifying an xs:dateTime in the renew request,
* eg. the subscriber requests to set the subscription expiration to a specific date/time.
*/
@Test public void renewWithDateTime() throws IOException {
Subscribe subscribe=new Subscribe();
ExpirationType exp=new ExpirationType();
exp.setValue(DurationAndDateUtil.convertToXMLString(DurationAndDateUtil.parseDurationOrTimestamp("2018-10-21T14:52:46.826+02:00")));
subscribe.setExpires(exp);
DeliveryType delivery=new DeliveryType();
subscribe.setDelivery(delivery);
subscribe.getDelivery().getContent().add(createDummyNotifyTo());
SubscribeResponse resp=eventSourceClient.subscribeOp(subscribe);
SubscriptionManagerEndpoint client=createSubscriptionManagerClient(resp.getSubscriptionManager().getReferenceParameters());
GetStatusResponse response=client.getStatusOp(new GetStatus());
String expirationBefore=response.getGrantedExpires().getValue();
System.out.println("EXPIRES before renew: " + expirationBefore);
Assert.assertTrue(expirationBefore.length() > 0);
Renew renewRequest=new Renew();
ExpirationType renewExp=new ExpirationType();
renewExp.setValue(DurationAndDateUtil.convertToXMLString(DurationAndDateUtil.parseDurationOrTimestamp("2056-10-21T14:54:46.826+02:00")));
renewRequest.setExpires(renewExp);
client.renewOp(renewRequest);
response=client.getStatusOp(new GetStatus());
String expirationAfter=response.getGrantedExpires().getValue();
System.out.println("EXPIRES after renew: " + expirationAfter);
Assert.assertFalse("Renew request should change the expiration time at least a bit",expirationAfter.equals(expirationBefore));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
/**
* Tests the Renew operation, while specifying an xs:duration in the renew request,
* eg. the subscriber requests to prolong the subscription by a specific amount of time.
*/
@Test public void renewWithDuration() throws IOException {
Subscribe subscribe=new Subscribe();
ExpirationType exp=new ExpirationType();
exp.setValue(DurationAndDateUtil.convertToXMLString(DurationAndDateUtil.parseDurationOrTimestamp("PT5M0S")));
subscribe.setExpires(exp);
DeliveryType delivery=new DeliveryType();
subscribe.setDelivery(delivery);
subscribe.getDelivery().getContent().add(createDummyNotifyTo());
SubscribeResponse resp=eventSourceClient.subscribeOp(subscribe);
SubscriptionManagerEndpoint client=createSubscriptionManagerClient(resp.getSubscriptionManager().getReferenceParameters());
GetStatusResponse response=client.getStatusOp(new GetStatus());
String expirationBefore=response.getGrantedExpires().getValue();
System.out.println("EXPIRES before renew: " + expirationBefore);
Assert.assertTrue(expirationBefore.length() > 0);
Renew renewRequest=new Renew();
ExpirationType renewExp=new ExpirationType();
renewExp.setValue(DurationAndDateUtil.convertToXMLString(DurationAndDateUtil.parseDurationOrTimestamp("PT10M0S")));
renewRequest.setExpires(renewExp);
client.renewOp(renewRequest);
response=client.getStatusOp(new GetStatus());
String expirationAfter=response.getGrantedExpires().getValue();
System.out.println("EXPIRES after renew: " + expirationAfter);
Assert.assertFalse("Renew request should change the expiration time at least a bit",expirationAfter.equals(expirationBefore));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
/**
* Creates a subscription and then retrieves its status from the Subscription Manager.
*/
@Test public void getStatus() throws Exception {
Subscribe subscribe=new Subscribe();
ExpirationType exp=new ExpirationType();
exp.setValue(DurationAndDateUtil.convertToXMLString(DurationAndDateUtil.parseDurationOrTimestamp("PT0S")));
subscribe.setExpires(exp);
DeliveryType delivery=new DeliveryType();
subscribe.setDelivery(delivery);
subscribe.getDelivery().getContent().add(createDummyNotifyTo());
SubscribeResponse resp=eventSourceClient.subscribeOp(subscribe);
SubscriptionManagerEndpoint client=createSubscriptionManagerClient(resp.getSubscriptionManager().getReferenceParameters());
GetStatusResponse response=client.getStatusOp(new GetStatus());
System.out.println("EXPIRES: " + response.getGrantedExpires().getValue());
Assert.assertTrue("GetStatus operation should return a XMLGregorianCalendar",DurationAndDateUtil.isXMLGregorianCalendar(response.getGrantedExpires().getValue()));
}
Class: org.apache.cxf.ws.eventing.misc.FilterEvaluationTest APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void simpleFilterEvaluationNegative() throws Exception {
Reader reader=new CharArrayReader("1 ".toCharArray());
Document doc=StaxUtils.read(reader);
FilterType filter=new FilterType();
filter.getContent().add("//ttx");
Assert.assertFalse(FilteringUtil.doesConformToFilter(doc.getDocumentElement(),filter));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void simpleFilterEvaluationPositive() throws Exception {
Reader reader=new CharArrayReader("1 ".toCharArray());
Document doc=StaxUtils.read(reader);
FilterType filter=new FilterType();
filter.getContent().add("//tt");
Assert.assertTrue(FilteringUtil.doesConformToFilter(doc.getDocumentElement(),filter));
}
Class: org.apache.cxf.ws.mex.MEXTest InternalCallVerifier NullVerifier
@Test public void testGet(){
JaxWsProxyFactoryBean proxyFac=new JaxWsProxyFactoryBean();
proxyFac.setAddress("local://Echo-mex");
proxyFac.getClientFactoryBean().setTransportId(LocalTransportFactory.TRANSPORT_ID);
MetadataExchange exc=proxyFac.create(MetadataExchange.class);
Metadata metadata=exc.get2004();
assertNotNull(metadata);
proxyFac=new JaxWsProxyFactoryBean();
proxyFac.setAddress("local://Echo");
proxyFac.getClientFactoryBean().setTransportId(LocalTransportFactory.TRANSPORT_ID);
exc=proxyFac.create(MetadataExchange.class);
metadata=exc.get2004();
assertNotNull(metadata);
}
Class: org.apache.cxf.ws.policy.AssertionBuilderRegistryImplTest IterativeVerifier UtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testBuildUnknownAssertion(){
Bus bus=control.createMock(Bus.class);
PolicyBuilder builder=control.createMock(PolicyBuilder.class);
EasyMock.expect(bus.getExtension(PolicyBuilder.class)).andReturn(builder).anyTimes();
AssertionBuilderRegistryImpl reg=new AssertionBuilderRegistryImpl(){
protected void loadDynamic(){
}
}
;
reg.setIgnoreUnknownAssertions(false);
Element[] elems=new Element[11];
QName[] qnames=new QName[11];
for (int i=0; i < 11; i++) {
qnames[i]=new QName("http://my.company.com","type" + Integer.toString(i));
elems[i]=control.createMock(Element.class);
EasyMock.expect(elems[i].getNamespaceURI()).andReturn(qnames[i].getNamespaceURI()).anyTimes();
EasyMock.expect(elems[i].getLocalName()).andReturn(qnames[i].getLocalPart()).anyTimes();
}
control.replay();
reg.setBus(bus);
assertTrue(!reg.isIgnoreUnknownAssertions());
try {
reg.build(elems[0]);
fail("Expected PolicyException not thrown.");
}
catch ( PolicyException ex) {
assertEquals("NO_ASSERTIONBUILDER_EXC",ex.getCode());
}
reg.setIgnoreUnknownAssertions(true);
assertTrue(reg.isIgnoreUnknownAssertions());
for (int i=0; i < 10; i++) {
Assertion assertion=reg.build(elems[i]);
assertTrue("Not a PrimitiveAsertion: " + assertion.getClass().getName(),assertion instanceof PrimitiveAssertion);
}
for (int i=9; i >= 0; i--) {
assertTrue(reg.build(elems[i]) instanceof PrimitiveAssertion);
}
assertTrue(reg.build(elems[10]) instanceof PrimitiveAssertion);
}
Class: org.apache.cxf.ws.policy.AssertionInfoMapTest APIUtilityVerifier BooleanVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testAllAssertionsIn(){
Policy nested=new Policy();
Assertion nb=new PrimitiveAssertion(new QName("http://x.y.z","b"));
nested.addAssertion(nb);
Policy p=new Policy();
Assertion a1=new PrimitiveAssertion(new QName("http://x.y.z","a"));
Assertion a2=new PrimitiveAssertion(new QName("http://x.y.z","a"));
Assertion b=new PrimitiveAssertion(new QName("http://x.y.z","b"));
Assertion c=new PolicyContainingPrimitiveAssertion(new QName("http://x.y.z","c"),false,false,nested);
All alt1=new All();
alt1.addAssertion(a1);
alt1.addAssertion(b);
All alt2=new All();
alt1.addAssertion(a2);
alt2.addAssertion(c);
ExactlyOne ea=new ExactlyOne();
ea.addPolicyComponent(alt1);
ea.addPolicyComponent(alt2);
p.addPolicyComponent(ea);
AssertionInfoMap aim=new AssertionInfoMap(p);
Collection listA=aim.getAssertionInfo(new QName("http://x.y.z","a"));
assertEquals("2 A assertions should've been added",2,listA.size());
AssertionInfo[] ais=listA.toArray(new AssertionInfo[]{});
assertTrue("Two different A instances should be added",ais[0].getAssertion() == a1 && ais[1].getAssertion() == a2 || ais[0].getAssertion() == a2 && ais[1].getAssertion() == a1);
Collection listB=aim.getAssertionInfo(new QName("http://x.y.z","b"));
assertEquals("2 B assertions should've been added",2,listB.size());
ais=listB.toArray(new AssertionInfo[]{});
assertTrue("Two different B instances should be added",ais[0].getAssertion() == nb && ais[1].getAssertion() == b || ais[0].getAssertion() == b && ais[1].getAssertion() == nb);
Collection listC=aim.getAssertionInfo(new QName("http://x.y.z","c"));
assertEquals("1 C assertion should've been added",1,listC.size());
ais=listC.toArray(new AssertionInfo[]{});
assertSame("One C instances should be added",ais[0].getAssertion(),c);
}
BooleanVerifier InternalCallVerifier
@Test public void testAlternativeSupported(){
PolicyAssertion a1=control.createMock(PolicyAssertion.class);
QName aqn=new QName("http://x.y.z","a");
EasyMock.expect(a1.getName()).andReturn(aqn).anyTimes();
PolicyAssertion a2=control.createMock(PolicyAssertion.class);
EasyMock.expect(a2.getName()).andReturn(aqn).anyTimes();
PolicyAssertion b=control.createMock(PolicyAssertion.class);
QName bqn=new QName("http://x.y.z","b");
EasyMock.expect(b.getName()).andReturn(bqn).anyTimes();
PolicyAssertion c=control.createMock(PolicyAssertion.class);
QName cqn=new QName("http://x.y.z","c");
EasyMock.expect(c.getName()).andReturn(cqn).anyTimes();
AssertionInfoMap aim=new AssertionInfoMap(CastUtils.cast(Collections.EMPTY_LIST,PolicyAssertion.class));
AssertionInfo ai1=new AssertionInfo(a1);
AssertionInfo ai2=new AssertionInfo(a2);
Collection ais=new ArrayList();
AssertionInfo bi=new AssertionInfo(b);
AssertionInfo ci=new AssertionInfo(c);
ais.add(ai1);
ais.add(ai2);
aim.put(aqn,ais);
aim.put(bqn,Collections.singleton(bi));
aim.put(cqn,Collections.singleton(ci));
ai2.setAsserted(true);
bi.setAsserted(true);
ci.setAsserted(true);
EasyMock.expect(a1.equal(a1)).andReturn(true).anyTimes();
EasyMock.expect(a2.equal(a2)).andReturn(true).anyTimes();
EasyMock.expect(b.equal(b)).andReturn(true).anyTimes();
EasyMock.expect(c.equal(c)).andReturn(true).anyTimes();
EasyMock.expect(a2.isAsserted(aim)).andReturn(true).anyTimes();
EasyMock.expect(b.isAsserted(aim)).andReturn(true).anyTimes();
EasyMock.expect(c.isAsserted(aim)).andReturn(true).anyTimes();
List alt1=new ArrayList();
alt1.add(a1);
alt1.add(b);
List alt2=new ArrayList();
alt2.add(a2);
alt2.add(c);
control.replay();
assertTrue(!aim.supportsAlternative(alt1,new ArrayList()));
assertTrue(aim.supportsAlternative(alt2,new ArrayList()));
control.verify();
}
Class: org.apache.cxf.ws.policy.EffectivePolicyImplTest UtilityVerifier InternalCallVerifier IdentityVerifier HybridVerifier
@Test public void testChooseAlternative(){
Message m=new MessageImpl();
EffectivePolicyImpl epi=new EffectivePolicyImpl();
Policy policy=new Policy();
epi.setPolicy(policy);
PolicyEngineImpl engine=control.createMock(PolicyEngineImpl.class);
Assertor assertor=control.createMock(Assertor.class);
AlternativeSelector selector=control.createMock(AlternativeSelector.class);
EasyMock.expect(engine.getAlternativeSelector()).andReturn(selector);
EasyMock.expect(selector.selectAlternative(policy,engine,assertor,null,m)).andReturn(null);
control.replay();
try {
epi.chooseAlternative(engine,assertor,m);
fail("Expected PolicyException not thrown.");
}
catch ( PolicyException ex) {
}
control.verify();
control.reset();
EasyMock.expect(engine.getAlternativeSelector()).andReturn(selector);
Collection alternative=new ArrayList();
EasyMock.expect(selector.selectAlternative(policy,engine,assertor,null,m)).andReturn(alternative);
control.replay();
epi.chooseAlternative(engine,assertor,m);
Collection choice=epi.getChosenAlternative();
assertSame(choice,alternative);
control.verify();
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testAccessors(){
EffectivePolicyImpl effectivePolicy=new EffectivePolicyImpl();
assertNull(effectivePolicy.getPolicy());
assertNull(effectivePolicy.getChosenAlternative());
assertNull(effectivePolicy.getInterceptors());
Policy p=control.createMock(Policy.class);
Assertion a=control.createMock(Assertion.class);
List la=Collections.singletonList(a);
List> li=createMockInterceptorList();
control.replay();
effectivePolicy.setPolicy(p);
assertSame(p,effectivePolicy.getPolicy());
effectivePolicy.setChosenAlternative(la);
assertSame(la,effectivePolicy.getChosenAlternative());
effectivePolicy.setInterceptors(li);
assertSame(li,effectivePolicy.getInterceptors());
control.verify();
}
InternalCallVerifier IdentityVerifier
@Test public void testInitialiseServerFaultPolicy(){
Message m=new MessageImpl();
EndpointInfo ei=control.createMock(EndpointInfo.class);
BindingFaultInfo bfi=control.createMock(BindingFaultInfo.class);
PolicyEngineImpl engine=control.createMock(PolicyEngineImpl.class);
BindingOperationInfo boi=control.createMock(BindingOperationInfo.class);
EasyMock.expect(bfi.getBindingOperation()).andReturn(boi).anyTimes();
EndpointPolicy endpointPolicy=control.createMock(EndpointPolicy.class);
EasyMock.expect(engine.getServerEndpointPolicy(ei,(Destination)null,m)).andReturn(endpointPolicy);
Policy ep=control.createMock(Policy.class);
EasyMock.expect(endpointPolicy.getPolicy()).andReturn(ep);
Policy op=control.createMock(Policy.class);
EasyMock.expect(engine.getAggregatedOperationPolicy(boi,m)).andReturn(op);
Policy merged=control.createMock(Policy.class);
EasyMock.expect(ep.merge(op)).andReturn(merged);
Policy fp=control.createMock(Policy.class);
EasyMock.expect(engine.getAggregatedFaultPolicy(bfi,m)).andReturn(fp);
EasyMock.expect(merged.merge(fp)).andReturn(merged);
EasyMock.expect(merged.normalize(null,true)).andReturn(merged);
control.replay();
EffectivePolicyImpl epi=new EffectivePolicyImpl();
epi.initialisePolicy(ei,boi,bfi,engine,m);
assertSame(merged,epi.getPolicy());
control.verify();
}
Class: org.apache.cxf.ws.policy.EndpointPolicyImplTest UtilityVerifier BooleanVerifier InternalCallVerifier IdentityVerifier HybridVerifier
@Test public void testChooseAlternative(){
Policy policy=new Policy();
PolicyEngineImpl engine=control.createMock(PolicyEngineImpl.class);
Assertor assertor=control.createMock(Assertor.class);
AlternativeSelector selector=control.createMock(AlternativeSelector.class);
Message m=new MessageImpl();
EndpointPolicyImpl epi=new EndpointPolicyImpl(null,engine,true,assertor);
epi.setPolicy(policy);
EasyMock.expect(engine.isEnabled()).andReturn(true).anyTimes();
EasyMock.expect(engine.getAlternativeSelector()).andReturn(selector);
EasyMock.expect(selector.selectAlternative(policy,engine,assertor,null,m)).andReturn(null);
control.replay();
try {
epi.chooseAlternative(m);
fail("Expected PolicyException not thrown.");
}
catch ( PolicyException ex) {
}
control.verify();
control.reset();
EasyMock.expect(engine.isEnabled()).andReturn(true).anyTimes();
EasyMock.expect(engine.getAlternativeSelector()).andReturn(selector);
Collection alternative=new ArrayList();
EasyMock.expect(selector.selectAlternative(policy,engine,assertor,null,m)).andReturn(alternative);
control.replay();
epi.chooseAlternative(m);
Collection choice=epi.getChosenAlternative();
assertSame(choice,alternative);
control.verify();
control.reset();
EasyMock.expect(engine.isEnabled()).andReturn(false).anyTimes();
EasyMock.expect(engine.getAlternativeSelector()).andReturn(null).anyTimes();
control.replay();
try {
epi.chooseAlternative(m);
}
catch ( Exception ex) {
fail("No Exception expected: " + ex);
}
choice=epi.getChosenAlternative();
assertTrue("not an empty list",choice != null && choice.isEmpty());
control.verify();
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testUpdatePolicy(){
EndpointPolicyImpl epi=new TestEndpointPolicy();
Policy p1=new Policy();
QName aqn1=new QName("http://x.y.z","a");
p1.addAssertion(mockAssertion(aqn1,5,true));
Policy p2=new Policy();
QName aqn2=new QName("http://x.y.z","b");
p2.addAssertion(mockAssertion(aqn2,5,true));
control.replay();
epi.setPolicy(p1.normalize(null,true));
Policy ep=epi.updatePolicy(p2,createMessage()).getPolicy();
List pops=CastUtils.cast(ep.getPolicyComponents(),ExactlyOne.class);
assertEquals("New policy must have 1 top level policy operator",1,pops.size());
List alts=CastUtils.cast(pops.get(0).getPolicyComponents(),All.class);
assertEquals("2 alternatives should be available",2,alts.size());
List assertions1=CastUtils.cast(alts.get(0).getAssertions(),PolicyAssertion.class);
assertEquals("1 assertion should be available",1,assertions1.size());
List assertions2=CastUtils.cast(alts.get(1).getAssertions(),PolicyAssertion.class);
assertEquals("1 assertion should be available",1,assertions2.size());
QName n1=assertions1.get(0).getName();
QName n2=assertions2.get(0).getName();
assertTrue("Policy was not merged",n1.equals(aqn1) && n2.equals(aqn2) || n1.equals(aqn2) && n2.equals(aqn1));
}
InternalCallVerifier IdentityVerifier
@Test public void testInitializePolicy(){
EndpointInfo ei=control.createMock(EndpointInfo.class);
PolicyEngineImpl engine=control.createMock(PolicyEngineImpl.class);
ServiceInfo si=control.createMock(ServiceInfo.class);
EasyMock.expect(ei.getService()).andReturn(si);
Policy sp=control.createMock(Policy.class);
EasyMock.expect(engine.getAggregatedServicePolicy(si,null)).andReturn(sp);
Policy ep=control.createMock(Policy.class);
EasyMock.expect(engine.getAggregatedEndpointPolicy(ei,null)).andReturn(ep);
Policy merged=control.createMock(Policy.class);
EasyMock.expect(sp.merge(ep)).andReturn(merged);
EasyMock.expect(merged.normalize(null,true)).andReturn(merged);
control.replay();
EndpointPolicyImpl epi=new EndpointPolicyImpl(ei,engine,true,null);
epi.initializePolicy(null);
assertSame(merged,epi.getPolicy());
control.verify();
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testAccessors(){
EndpointPolicyImpl epi=new EndpointPolicyImpl();
Message m=new MessageImpl();
assertNull(epi.getPolicy());
assertNull(epi.getChosenAlternative());
assertNull(epi.getInterceptors(m));
assertNull(epi.getFaultInterceptors(m));
Policy p=control.createMock(Policy.class);
Assertion a=control.createMock(Assertion.class);
List la=Collections.singletonList(a);
List> li=createMockInterceptorList();
control.replay();
epi.setPolicy(p);
assertSame(p,epi.getPolicy());
epi.setChosenAlternative(la);
assertSame(la,epi.getChosenAlternative());
epi.setInterceptors(li);
assertSame(li,epi.getInterceptors(m));
epi.setFaultInterceptors(li);
assertSame(li,epi.getFaultInterceptors(m));
epi.setVocabulary(la);
assertSame(la,epi.getVocabulary(m));
epi.setFaultVocabulary(la);
assertSame(la,epi.getFaultVocabulary(m));
control.verify();
}
Class: org.apache.cxf.ws.policy.IgnorablePolicyInterceptorProviderTest BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testProvider(){
Bus bus=null;
try {
bus=new SpringBusFactory().createBus("/org/apache/cxf/ws/policy/ignorable-policy.xml",false);
PolicyInterceptorProviderRegistry pipreg=bus.getExtension(PolicyInterceptorProviderRegistry.class);
assertNotNull(pipreg);
Set pips=pipreg.get(ONEWAY_QNAME);
assertNotNull(pips);
assertFalse(pips.isEmpty());
Set pips2=pipreg.get(DUPLEX_QNAME);
assertNotNull(pips2);
assertFalse(pips2.isEmpty());
assertEquals(pips.iterator().next(),pips2.iterator().next());
}
finally {
if (null != bus) {
bus.shutdown(true);
BusFactory.setDefaultBus(null);
}
}
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testInterceptorAssertion(){
Bus bus=null;
try {
bus=new SpringBusFactory().createBus("/org/apache/cxf/ws/policy/ignorable-policy.xml",false);
PolicyInterceptorProviderRegistry pipreg=bus.getExtension(PolicyInterceptorProviderRegistry.class);
assertNotNull(pipreg);
Set pips=pipreg.get(ONEWAY_QNAME);
assertNotNull(pips);
assertFalse(pips.isEmpty());
PolicyInterceptorProvider pip=pips.iterator().next();
List> list;
list=CastUtils.cast(pip.getOutInterceptors());
verifyAssertion(list);
list=CastUtils.cast(pip.getInInterceptors());
verifyAssertion(list);
list=CastUtils.cast(pip.getOutFaultInterceptors());
verifyAssertion(list);
list=CastUtils.cast(pip.getInFaultInterceptors());
verifyAssertion(list);
}
finally {
if (null != bus) {
bus.shutdown(true);
BusFactory.setDefaultBus(null);
}
}
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testTwoBuses(){
ClassPathXmlApplicationContext context=null;
Bus cxf1=null;
Bus cxf2=null;
try {
context=new ClassPathXmlApplicationContext("/org/apache/cxf/ws/policy/ignorable-policy2.xml");
cxf1=(Bus)context.getBean("cxf1");
assertNotNull(cxf1);
cxf2=(Bus)context.getBean("cxf2");
assertNotNull(cxf2);
PolicyInterceptorProviderRegistry pipreg1=cxf1.getExtension(PolicyInterceptorProviderRegistry.class);
assertNotNull(pipreg1);
PolicyInterceptorProviderRegistry pipreg2=cxf2.getExtension(PolicyInterceptorProviderRegistry.class);
assertNotNull(pipreg2);
Set pips1=pipreg1.get(ONEWAY_QNAME);
assertNotNull(pips1);
assertFalse(pips1.isEmpty());
Set pips2=pipreg2.get(ONEWAY_QNAME);
assertNotNull(pips2);
assertFalse(pips2.isEmpty());
assertEquals(pips1.iterator().next(),pips2.iterator().next());
context.close();
}
finally {
if (null != cxf1) {
cxf1.shutdown(true);
BusFactory.setDefaultBus(null);
}
}
}
Class: org.apache.cxf.ws.policy.PolicyBuilderTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testGetPolicyReference() throws Exception {
String name="/samples/test26.xml";
InputStream is=PolicyBuilderTest.class.getResourceAsStream(name);
PolicyReference pr=builder.getPolicyReference(is);
assertEquals("#PolicyA",pr.getURI());
name="/samples/test27.xml";
is=PolicyBuilderTest.class.getResourceAsStream(name);
pr=builder.getPolicyReference(is);
assertEquals("http://sample.org/test.wsdl#PolicyA",pr.getURI());
}
APIUtilityVerifier IterativeVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetPolicy() throws Exception {
String name="/samples/test25.xml";
InputStream is=PolicyBuilderTest.class.getResourceAsStream(name);
Policy p=builder.getPolicy(is);
assertNotNull(p);
List a=CastUtils.cast(p.getAssertions(),PolicyComponent.class);
assertEquals(3,a.size());
for (int i=0; i < 3; i++) {
assertEquals(Constants.TYPE_ASSERTION,a.get(i).getType());
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testGetPolicyWithAttributes() throws Exception {
String name="/samples/test28.xml";
InputStream is=PolicyBuilderTest.class.getResourceAsStream(name);
Policy p=builder.getPolicy(is);
assertNotNull(p);
assertTrue(p.getAttributes().size() >= 2);
QName n1=new QName("nonsattr");
Object v1=p.getAttribute(n1);
assertNotNull(v1);
QName n2=new QName("http://x.y.z","nsattr");
Object v2=p.getAttribute(n2);
assertNotNull(v2);
}
Class: org.apache.cxf.ws.policy.PolicyEngineImplInitTest InternalCallVerifier EqualityVerifier
@Test public void testPolicyInterceptors() throws Exception {
Assert.assertEquals("should only have one PolicyOutInterceptor",bus.getOutInterceptors().size(),1);
Assert.assertEquals("should only have one PolicyInInterceptor",bus.getInInterceptors().size(),1);
}
Class: org.apache.cxf.ws.policy.PolicyEngineTest InternalCallVerifier IdentityVerifier
@Test public void testSetEffectiveClientRequestPolicy() throws Exception {
engine=new PolicyEngineImpl();
EndpointInfo ei=createMockEndpointInfo();
BindingOperationInfo boi=createMockBindingOperationInfo();
EffectivePolicy effectivePolicy=control.createMock(EffectivePolicy.class);
control.replay();
engine.setEffectiveClientRequestPolicy(ei,boi,effectivePolicy);
assertSame(effectivePolicy,engine.getEffectiveClientRequestPolicy(ei,boi,(Conduit)null,msg));
control.verify();
}
BooleanVerifier InternalCallVerifier IdentityVerifier HybridVerifier
@Test public void testGetAggregatedServicePolicy(){
engine=new PolicyEngineImpl();
ServiceInfo si=control.createMock(ServiceInfo.class);
control.replay();
Policy p=engine.getAggregatedServicePolicy(si,null);
assertTrue(p.isEmpty());
control.verify();
control.reset();
PolicyProvider provider1=control.createMock(PolicyProvider.class);
engine.getPolicyProviders().add(provider1);
Policy p1=control.createMock(Policy.class);
EasyMock.expect(provider1.getEffectivePolicy(si,null)).andReturn(p1);
control.replay();
assertSame(p1,engine.getAggregatedServicePolicy(si,null));
control.verify();
control.reset();
PolicyProvider provider2=control.createMock(PolicyProvider.class);
engine.getPolicyProviders().add(provider2);
Policy p2=control.createMock(Policy.class);
Policy p3=control.createMock(Policy.class);
EasyMock.expect(provider1.getEffectivePolicy(si,null)).andReturn(p1);
EasyMock.expect(provider2.getEffectivePolicy(si,null)).andReturn(p2);
EasyMock.expect(p1.merge(p2)).andReturn(p3);
control.replay();
assertSame(p3,engine.getAggregatedServicePolicy(si,null));
control.verify();
}
InternalCallVerifier IdentityVerifier
@Test public void testSetEffectiveClientFaultPolicy() throws Exception {
engine=new PolicyEngineImpl();
EndpointInfo ei=createMockEndpointInfo();
BindingFaultInfo bfi=new BindingFaultInfo(null,null);
EffectivePolicy epi=control.createMock(EffectivePolicy.class);
engine.setEffectiveClientFaultPolicy(ei,bfi,epi);
assertSame(epi,engine.getEffectiveClientFaultPolicy(ei,null,bfi,msg));
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier
@Test public void testGetEndpointPolicyServerSide() throws Exception {
Method m=PolicyEngineImpl.class.getDeclaredMethod("createEndpointPolicyInfo",new Class[]{EndpointInfo.class,boolean.class,Assertor.class,Message.class});
engine=EasyMock.createMockBuilder(PolicyEngineImpl.class).addMockedMethod(m).createMock(control);
engine.init();
EndpointInfo ei=createMockEndpointInfo();
AssertingDestination destination=control.createMock(AssertingDestination.class);
EndpointPolicyImpl epi=control.createMock(EndpointPolicyImpl.class);
EasyMock.expect(engine.createEndpointPolicyInfo(ei,false,destination,msg)).andReturn(epi);
control.replay();
assertSame(epi,engine.getServerEndpointPolicy(ei,destination,msg));
control.verify();
}
BooleanVerifier InternalCallVerifier IdentityVerifier HybridVerifier
@Test public void testGetAggregatedFaultPolicy(){
engine=new PolicyEngineImpl();
BindingFaultInfo bfi=control.createMock(BindingFaultInfo.class);
control.replay();
Policy p=engine.getAggregatedFaultPolicy(bfi,null);
assertTrue(p.isEmpty());
control.verify();
control.reset();
PolicyProvider provider1=control.createMock(PolicyProvider.class);
engine.getPolicyProviders().add(provider1);
Policy p1=control.createMock(Policy.class);
EasyMock.expect(provider1.getEffectivePolicy(bfi,null)).andReturn(p1);
control.replay();
assertSame(p1,engine.getAggregatedFaultPolicy(bfi,null));
control.verify();
control.reset();
PolicyProvider provider2=control.createMock(PolicyProvider.class);
engine.getPolicyProviders().add(provider2);
Policy p2=control.createMock(Policy.class);
Policy p3=control.createMock(Policy.class);
EasyMock.expect(provider1.getEffectivePolicy(bfi,null)).andReturn(p1);
EasyMock.expect(provider2.getEffectivePolicy(bfi,null)).andReturn(p2);
EasyMock.expect(p1.merge(p2)).andReturn(p3);
control.replay();
assertSame(p3,engine.getAggregatedFaultPolicy(bfi,null));
control.verify();
}
InternalCallVerifier IdentityVerifier
@Test public void testSetEffectiveServerFaultPolicy() throws Exception {
engine=new PolicyEngineImpl();
EndpointInfo ei=createMockEndpointInfo();
BindingFaultInfo bfi=new BindingFaultInfo(null,null);
EffectivePolicy epi=control.createMock(EffectivePolicy.class);
engine.setEffectiveServerFaultPolicy(ei,bfi,epi);
assertSame(epi,engine.getEffectiveServerFaultPolicy(ei,null,bfi,(Destination)null,msg));
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier
@Test public void testGetEffectiveServerRequestPolicyInfo() throws Exception {
Method m=PolicyEngineImpl.class.getDeclaredMethod("createOutPolicyInfo",new Class[]{});
engine=EasyMock.createMockBuilder(PolicyEngineImpl.class).addMockedMethod(m).createMock(control);
engine.init();
EndpointInfo ei=createMockEndpointInfo();
BindingOperationInfo boi=createMockBindingOperationInfo();
EffectivePolicyImpl epi=control.createMock(EffectivePolicyImpl.class);
EasyMock.expect(engine.createOutPolicyInfo()).andReturn(epi);
epi.initialise(ei,boi,engine,false,true,msg);
EasyMock.expectLastCall();
control.replay();
assertSame(epi,engine.getEffectiveServerRequestPolicy(ei,boi,msg));
assertSame(epi,engine.getEffectiveServerRequestPolicy(ei,boi,msg));
control.verify();
}
InternalCallVerifier IdentityVerifier
@Test public void testSetEffectiveServerRequestPolicy() throws Exception {
engine=new PolicyEngineImpl();
EndpointInfo ei=createMockEndpointInfo();
BindingOperationInfo boi=createMockBindingOperationInfo();
EffectivePolicy effectivePolicy=control.createMock(EffectivePolicy.class);
control.replay();
engine.setEffectiveServerRequestPolicy(ei,boi,effectivePolicy);
assertSame(effectivePolicy,engine.getEffectiveServerRequestPolicy(ei,boi,msg));
control.verify();
}
BooleanVerifier InternalCallVerifier IdentityVerifier HybridVerifier
@Test public void testGetAggregatedEndpointPolicy() throws Exception {
engine=new PolicyEngineImpl();
EndpointInfo ei=createMockEndpointInfo();
control.replay();
Policy p=engine.getAggregatedEndpointPolicy(ei,null);
assertTrue(p.isEmpty());
control.verify();
control.reset();
PolicyProvider provider1=control.createMock(PolicyProvider.class);
engine.getPolicyProviders().add(provider1);
Policy p1=control.createMock(Policy.class);
EasyMock.expect(provider1.getEffectivePolicy(ei,null)).andReturn(p1);
control.replay();
assertSame(p1,engine.getAggregatedEndpointPolicy(ei,null));
control.verify();
control.reset();
PolicyProvider provider2=control.createMock(PolicyProvider.class);
engine.getPolicyProviders().add(provider2);
Policy p2=control.createMock(Policy.class);
Policy p3=control.createMock(Policy.class);
EasyMock.expect(provider1.getEffectivePolicy(ei,null)).andReturn(p1);
EasyMock.expect(provider2.getEffectivePolicy(ei,null)).andReturn(p2);
EasyMock.expect(p1.merge(p2)).andReturn(p3);
control.replay();
assertSame(p3,engine.getAggregatedEndpointPolicy(ei,null));
control.verify();
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier
@Test public void testGetEffectiveClientFaultPolicy() throws Exception {
Method m=PolicyEngineImpl.class.getDeclaredMethod("createOutPolicyInfo",new Class[]{});
engine=EasyMock.createMockBuilder(PolicyEngineImpl.class).addMockedMethod(m).createMock(control);
engine.init();
EndpointInfo ei=createMockEndpointInfo();
BindingFaultInfo bfi=new BindingFaultInfo(null,null);
EffectivePolicyImpl epi=control.createMock(EffectivePolicyImpl.class);
EasyMock.expect(engine.createOutPolicyInfo()).andReturn(epi);
epi.initialisePolicy(ei,null,bfi,engine,msg);
EasyMock.expectLastCall();
control.replay();
assertSame(epi,engine.getEffectiveClientFaultPolicy(ei,null,bfi,msg));
assertSame(epi,engine.getEffectiveClientFaultPolicy(ei,null,bfi,msg));
control.verify();
}
InternalCallVerifier IdentityVerifier
@Test public void testEndpointPolicyWithEqualPolicies() throws Exception {
engine=new PolicyEngineImpl();
EndpointInfo ei=createMockEndpointInfo();
ServiceInfo si=control.createMock(ServiceInfo.class);
ei.setService(si);
si.getExtensor(Policy.class);
EasyMock.expectLastCall().andReturn(null).times(2);
EndpointPolicyImpl epi=control.createMock(EndpointPolicyImpl.class);
control.replay();
engine.setServerEndpointPolicy(ei,epi);
engine.setClientEndpointPolicy(ei,epi);
assertSame(epi,engine.getClientEndpointPolicy(ei,(Conduit)null,msg));
assertSame(epi,engine.getServerEndpointPolicy(ei,(Destination)null,msg));
control.reset();
ei.setService(si);
Policy p=new Policy();
si.getExtensor(Policy.class);
EasyMock.expectLastCall().andReturn(p).times(2);
epi.getPolicy();
EasyMock.expectLastCall().andReturn(p).times(2);
control.replay();
assertSame(epi,engine.getServerEndpointPolicy(ei,(Destination)null,msg));
}
InternalCallVerifier IdentityVerifier
@Test public void testSetEffectiveServerResponsePolicy() throws Exception {
engine=new PolicyEngineImpl();
EndpointInfo ei=createMockEndpointInfo();
BindingOperationInfo boi=createMockBindingOperationInfo();
EffectivePolicy effectivePolicy=control.createMock(EffectivePolicy.class);
control.replay();
engine.setEffectiveServerResponsePolicy(ei,boi,effectivePolicy);
assertSame(effectivePolicy,engine.getEffectiveServerResponsePolicy(ei,boi,(Destination)null,null,msg));
control.verify();
}
BooleanVerifier InternalCallVerifier IdentityVerifier HybridVerifier
@Test public void testGetAggregatedOperationPolicy() throws Exception {
engine=new PolicyEngineImpl();
BindingOperationInfo boi=createMockBindingOperationInfo();
control.replay();
Policy p=engine.getAggregatedOperationPolicy(boi,null);
assertTrue(p.isEmpty());
control.verify();
control.reset();
PolicyProvider provider1=control.createMock(PolicyProvider.class);
engine.getPolicyProviders().add(provider1);
Policy p1=control.createMock(Policy.class);
EasyMock.expect(provider1.getEffectivePolicy(boi,null)).andReturn(p1);
control.replay();
assertSame(p1,engine.getAggregatedOperationPolicy(boi,null));
control.verify();
control.reset();
PolicyProvider provider2=control.createMock(PolicyProvider.class);
engine.getPolicyProviders().add(provider2);
Policy p2=control.createMock(Policy.class);
Policy p3=control.createMock(Policy.class);
EasyMock.expect(provider1.getEffectivePolicy(boi,null)).andReturn(p1);
EasyMock.expect(provider2.getEffectivePolicy(boi,null)).andReturn(p2);
EasyMock.expect(p1.merge(p2)).andReturn(p3);
control.replay();
assertSame(p3,engine.getAggregatedOperationPolicy(boi,null));
control.verify();
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier
@Test public void testGetEffectiveServerFaultPolicy() throws Exception {
Method m=PolicyEngineImpl.class.getDeclaredMethod("createOutPolicyInfo",new Class[]{});
engine=EasyMock.createMockBuilder(PolicyEngineImpl.class).addMockedMethod(m).createMock(control);
engine.init();
EndpointInfo ei=createMockEndpointInfo();
BindingFaultInfo bfi=new BindingFaultInfo(null,null);
AssertingDestination destination=control.createMock(AssertingDestination.class);
EffectivePolicyImpl epi=control.createMock(EffectivePolicyImpl.class);
EasyMock.expect(engine.createOutPolicyInfo()).andReturn(epi);
epi.initialise(ei,null,bfi,engine,destination,msg);
EasyMock.expectLastCall();
control.replay();
assertSame(epi,engine.getEffectiveServerFaultPolicy(ei,null,bfi,destination,msg));
assertSame(epi,engine.getEffectiveServerFaultPolicy(ei,null,bfi,destination,msg));
control.verify();
}
BooleanVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testAddAssertions(){
engine=new PolicyEngineImpl();
Collection assertions=new ArrayList();
Assertion a=control.createMock(Assertion.class);
EasyMock.expect(a.getType()).andReturn(Constants.TYPE_ASSERTION);
EasyMock.expect(a.isOptional()).andReturn(true);
control.replay();
engine.addAssertions(a,false,assertions);
assertTrue(assertions.isEmpty());
control.verify();
control.reset();
EasyMock.expect(a.getType()).andReturn(Constants.TYPE_ASSERTION);
control.replay();
engine.addAssertions(a,true,assertions);
assertEquals(1,assertions.size());
assertSame(a,assertions.iterator().next());
control.verify();
assertions.clear();
Policy p=new Policy();
a=new PrimitiveAssertion(new QName("http://x.y.z","a"));
p.addAssertion(a);
engine.getRegistry().register("ab",p);
PolicyReference pr=new PolicyReference();
pr.setURI("#ab");
engine.addAssertions(pr,false,assertions);
assertEquals(1,assertions.size());
assertSame(a,assertions.iterator().next());
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier
@Test public void testGetEffectiveClientRequestPolicy() throws Exception {
Method m=PolicyEngineImpl.class.getDeclaredMethod("createOutPolicyInfo",new Class[]{});
engine=EasyMock.createMockBuilder(PolicyEngineImpl.class).addMockedMethod(m).createMock(control);
engine.init();
EndpointInfo ei=createMockEndpointInfo();
BindingOperationInfo boi=createMockBindingOperationInfo();
AssertingConduit conduit=control.createMock(AssertingConduit.class);
EffectivePolicyImpl epi=control.createMock(EffectivePolicyImpl.class);
EasyMock.expect(engine.createOutPolicyInfo()).andReturn(epi);
epi.initialise(ei,boi,engine,conduit,true,true,msg);
EasyMock.expectLastCall();
control.replay();
assertSame(epi,engine.getEffectiveClientRequestPolicy(ei,boi,conduit,msg));
assertSame(epi,engine.getEffectiveClientRequestPolicy(ei,boi,conduit,msg));
control.verify();
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier
@Test public void testGetEffectiveServerResponsePolicy() throws Exception {
Method m=PolicyEngineImpl.class.getDeclaredMethod("createOutPolicyInfo",new Class[]{});
engine=EasyMock.createMockBuilder(PolicyEngineImpl.class).addMockedMethod(m).createMock(control);
engine.init();
EndpointInfo ei=createMockEndpointInfo();
BindingOperationInfo boi=createMockBindingOperationInfo();
AssertingDestination destination=control.createMock(AssertingDestination.class);
EffectivePolicyImpl epi=control.createMock(EffectivePolicyImpl.class);
EasyMock.expect(engine.createOutPolicyInfo()).andReturn(epi);
epi.initialise(ei,boi,engine,destination,false,false,null);
EasyMock.expectLastCall();
control.replay();
assertSame(epi,engine.getEffectiveServerResponsePolicy(ei,boi,destination,null,msg));
assertSame(epi,engine.getEffectiveServerResponsePolicy(ei,boi,destination,null,msg));
control.verify();
}
BooleanVerifier InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testAccessors() throws Exception {
engine=new PolicyEngineImpl(false);
assertNotNull(engine.getRegistry());
assertNull(engine.getBus());
assertNotNull(engine.getPolicyProviders());
assertNull(engine.getAlternativeSelector());
assertTrue(!engine.isEnabled());
Bus bus=new ExtensionManagerBus();
engine.setBus(bus);
List providers=CastUtils.cast(Collections.EMPTY_LIST,PolicyProvider.class);
engine.setPolicyProviders(providers);
PolicyRegistry reg=control.createMock(PolicyRegistry.class);
engine.setRegistry(reg);
engine.setEnabled(true);
AlternativeSelector selector=control.createMock(AlternativeSelector.class);
engine.setAlternativeSelector(selector);
assertSame(bus,engine.getBus());
assertSame(reg,engine.getRegistry());
assertTrue(engine.isEnabled());
assertSame(selector,engine.getAlternativeSelector());
assertNotNull(engine.createOutPolicyInfo());
bus.shutdown(true);
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier
@Test public void testGetEffectiveClientResponsePolicy() throws Exception {
Method m=PolicyEngineImpl.class.getDeclaredMethod("createOutPolicyInfo",new Class[]{});
engine=EasyMock.createMockBuilder(PolicyEngineImpl.class).addMockedMethod(m).createMock(control);
engine.init();
EndpointInfo ei=createMockEndpointInfo();
BindingOperationInfo boi=createMockBindingOperationInfo();
EffectivePolicyImpl epi=control.createMock(EffectivePolicyImpl.class);
EasyMock.expect(engine.createOutPolicyInfo()).andReturn(epi);
epi.initialise(ei,boi,engine,true,false,msg);
EasyMock.expectLastCall();
control.replay();
assertSame(epi,engine.getEffectiveClientResponsePolicy(ei,boi,msg));
assertSame(epi,engine.getEffectiveClientResponsePolicy(ei,boi,msg));
control.verify();
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testGetAssertions() throws NoSuchMethodException {
Method m=PolicyEngineImpl.class.getDeclaredMethod("addAssertions",new Class[]{PolicyComponent.class,boolean.class,Collection.class});
engine=EasyMock.createMockBuilder(PolicyEngineImpl.class).addMockedMethod(m).createMock(control);
PolicyAssertion a=control.createMock(PolicyAssertion.class);
EasyMock.expect(a.getType()).andReturn(Constants.TYPE_ASSERTION);
EasyMock.expect(a.isOptional()).andReturn(true);
control.replay();
assertTrue(engine.getAssertions(a,false).isEmpty());
control.verify();
control.reset();
EasyMock.expect(a.getType()).andReturn(Constants.TYPE_ASSERTION);
control.replay();
Collection ca=engine.getAssertions(a,true);
assertEquals(1,ca.size());
assertSame(a,ca.iterator().next());
control.verify();
control.reset();
Policy p=control.createMock(Policy.class);
EasyMock.expect(p.getType()).andReturn(Constants.TYPE_POLICY);
engine.addAssertions(EasyMock.eq(p),EasyMock.eq(false),CastUtils.cast(EasyMock.isA(Collection.class),Assertion.class));
EasyMock.expectLastCall();
control.replay();
assertTrue(engine.getAssertions(p,false).isEmpty());
control.verify();
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier
@Test public void testCreateEndpointPolicyInfo() throws Exception {
Method m1=PolicyEngineImpl.class.getDeclaredMethod("createEndpointPolicyInfo",new Class[]{EndpointInfo.class,boolean.class,Assertor.class,Message.class});
engine=EasyMock.createMockBuilder(PolicyEngineImpl.class).addMockedMethod(m1).createMock(control);
engine.init();
EndpointInfo ei=createMockEndpointInfo();
Assertor assertor=control.createMock(Assertor.class);
EndpointPolicyImpl epi=control.createMock(EndpointPolicyImpl.class);
EasyMock.expect(engine.createEndpointPolicyInfo(ei,false,assertor,msg)).andReturn(epi);
control.replay();
assertSame(epi,engine.createEndpointPolicyInfo(ei,false,assertor,msg));
control.verify();
}
InternalCallVerifier IdentityVerifier
@Test public void testSetEffectiveClientResponsePolicy() throws Exception {
engine=new PolicyEngineImpl();
EndpointInfo ei=createMockEndpointInfo();
BindingOperationInfo boi=createMockBindingOperationInfo();
EffectivePolicy epi=control.createMock(EffectivePolicy.class);
control.replay();
engine.setEffectiveClientResponsePolicy(ei,boi,epi);
assertSame(epi,engine.getEffectiveClientResponsePolicy(ei,boi,msg));
control.verify();
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier
@Test public void testGetEndpointPolicyClientSide() throws Exception {
Method m=PolicyEngineImpl.class.getDeclaredMethod("createEndpointPolicyInfo",new Class[]{EndpointInfo.class,boolean.class,Assertor.class,Message.class});
engine=EasyMock.createMockBuilder(PolicyEngineImpl.class).addMockedMethod(m).createMock(control);
engine.init();
EndpointInfo ei=createMockEndpointInfo();
AssertingConduit conduit=control.createMock(AssertingConduit.class);
EndpointPolicyImpl epi=control.createMock(EndpointPolicyImpl.class);
EasyMock.expect(engine.createEndpointPolicyInfo(ei,true,conduit,msg)).andReturn(epi);
control.replay();
assertSame(epi,engine.getClientEndpointPolicy(ei,conduit,msg));
control.verify();
}
BooleanVerifier InternalCallVerifier IdentityVerifier HybridVerifier
@Test public void testGetAggregatedMessagePolicy(){
engine=new PolicyEngineImpl();
BindingMessageInfo bmi=control.createMock(BindingMessageInfo.class);
control.replay();
Policy p=engine.getAggregatedMessagePolicy(bmi,null);
assertTrue(p.isEmpty());
control.verify();
control.reset();
PolicyProvider provider1=control.createMock(PolicyProvider.class);
engine.getPolicyProviders().add(provider1);
Policy p1=control.createMock(Policy.class);
EasyMock.expect(provider1.getEffectivePolicy(bmi,null)).andReturn(p1);
control.replay();
assertSame(p1,engine.getAggregatedMessagePolicy(bmi,null));
control.verify();
control.reset();
PolicyProvider provider2=control.createMock(PolicyProvider.class);
engine.getPolicyProviders().add(provider2);
Policy p2=control.createMock(Policy.class);
Policy p3=control.createMock(Policy.class);
EasyMock.expect(provider1.getEffectivePolicy(bmi,null)).andReturn(p1);
EasyMock.expect(provider2.getEffectivePolicy(bmi,null)).andReturn(p2);
EasyMock.expect(p1.merge(p2)).andReturn(p3);
control.replay();
assertSame(p3,engine.getAggregatedMessagePolicy(bmi,null));
control.verify();
}
Class: org.apache.cxf.ws.policy.PolicyExtensionsTest InternalCallVerifier NullVerifier
@Test public void testCXF4258(){
Bus bus=null;
try {
bus=new SpringBusFactory().createBus("/org/apache/cxf/ws/policy/disable-policy-bus.xml",false);
AssertionBuilderRegistry abr=bus.getExtension(AssertionBuilderRegistry.class);
assertNotNull(abr);
PolicyEngine e=bus.getExtension(PolicyEngine.class);
assertNotNull(e);
assertNoPolicyInterceptors(bus.getInInterceptors());
assertNoPolicyInterceptors(bus.getInFaultInterceptors());
assertNoPolicyInterceptors(bus.getOutFaultInterceptors());
assertNoPolicyInterceptors(bus.getOutInterceptors());
}
finally {
if (null != bus) {
bus.shutdown(true);
BusFactory.setDefaultBus(null);
}
}
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testExtensions(){
Bus bus=null;
try {
bus=new SpringBusFactory().createBus("/org/apache/cxf/ws/policy/policy-bus.xml",false);
AssertionBuilderRegistry abr=bus.getExtension(AssertionBuilderRegistry.class);
assertNotNull(abr);
AssertionBuilder> ab=abr.getBuilder(KNOWN);
assertNotNull(ab);
ab=abr.getBuilder(UNKNOWN);
assertNull(ab);
PolicyInterceptorProviderRegistry pipr=bus.getExtension(PolicyInterceptorProviderRegistry.class);
assertNotNull(pipr);
Set pips=pipr.get(KNOWN);
assertNotNull(pips);
assertFalse(pips.isEmpty());
pips=pipr.get(UNKNOWN);
assertNotNull(pips);
assertTrue(pips.isEmpty());
DomainExpressionBuilderRegistry debr=bus.getExtension(DomainExpressionBuilderRegistry.class);
assertNotNull(debr);
DomainExpressionBuilder deb=debr.get(KNOWN_DOMAIN_EXPR_TYPE);
assertNotNull(deb);
deb=debr.get(UNKNOWN);
assertNull(deb);
PolicyEngine pe=bus.getExtension(PolicyEngine.class);
assertNotNull(pe);
PolicyEngineImpl engine=(PolicyEngineImpl)pe;
assertNotNull(engine.getPolicyProviders());
assertNotNull(engine.getRegistry());
Collection pps=engine.getPolicyProviders();
assertEquals(3,pps.size());
boolean wsdlProvider=false;
boolean externalProvider=false;
boolean serviceProvider=false;
for ( PolicyProvider pp : pps) {
if (pp instanceof Wsdl11AttachmentPolicyProvider) {
wsdlProvider=true;
}
else if (pp instanceof ExternalAttachmentProvider) {
externalProvider=true;
}
else if (pp instanceof ServiceModelPolicyProvider) {
serviceProvider=true;
}
}
assertTrue(wsdlProvider);
assertTrue(externalProvider);
assertTrue(serviceProvider);
PolicyBuilder builder=bus.getExtension(PolicyBuilder.class);
assertNotNull(builder);
}
finally {
if (null != bus) {
bus.shutdown(true);
BusFactory.setDefaultBus(null);
}
}
}
Class: org.apache.cxf.ws.policy.PolicyInterceptorProviderRegistryImplTest BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testGetNotNull(){
PolicyInterceptorProviderRegistryImpl reg=new PolicyInterceptorProviderRegistryImpl();
assertNotNull(reg.get(ASSERTION));
assertTrue(reg.get(ASSERTION).isEmpty());
assertNotNull(reg.getInInterceptorsForAssertion(ASSERTION));
assertTrue(reg.getInInterceptorsForAssertion(ASSERTION).isEmpty());
assertNotNull(reg.getOutInterceptorsForAssertion(ASSERTION));
assertTrue(reg.getOutInterceptorsForAssertion(ASSERTION).isEmpty());
assertNotNull(reg.getInFaultInterceptorsForAssertion(ASSERTION));
assertTrue(reg.getInFaultInterceptorsForAssertion(ASSERTION).isEmpty());
assertNotNull(reg.getOutFaultInterceptorsForAssertion(ASSERTION));
assertTrue(reg.getOutFaultInterceptorsForAssertion(ASSERTION).isEmpty());
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test @SuppressWarnings("unchecked") public void testRegister(){
PolicyInterceptorProviderRegistryImpl reg=new PolicyInterceptorProviderRegistryImpl();
PolicyInterceptorProvider pp=control.createMock(PolicyInterceptorProvider.class);
Interceptor pi1=control.createMock(Interceptor.class);
Interceptor pi2=control.createMock(Interceptor.class);
Interceptor pif=control.createMock(Interceptor.class);
Interceptor po=control.createMock(Interceptor.class);
Interceptor pof=control.createMock(Interceptor.class);
List> pil=new ArrayList>();
pil.add(pi1);
pil.add(pi2);
List> pifl=new ArrayList>();
pifl.add(pif);
List> pol=new ArrayList>();
pol.add(po);
List> pofl=new ArrayList>();
pofl.add(pof);
EasyMock.expect(pp.getInInterceptors()).andReturn(pil);
EasyMock.expect(pp.getInFaultInterceptors()).andReturn(pifl);
EasyMock.expect(pp.getOutInterceptors()).andReturn(pol);
EasyMock.expect(pp.getOutFaultInterceptors()).andReturn(pofl);
Collection assertionTypes=new ArrayList();
assertionTypes.add(ASSERTION);
EasyMock.expect(pp.getAssertionTypes()).andReturn(assertionTypes);
control.replay();
reg.register(pp);
assertEquals(pil,reg.getInInterceptorsForAssertion(ASSERTION));
assertEquals(pifl,reg.getInFaultInterceptorsForAssertion(ASSERTION));
assertEquals(pol,reg.getOutInterceptorsForAssertion(ASSERTION));
assertEquals(pofl,reg.getOutFaultInterceptorsForAssertion(ASSERTION));
assertTrue(reg.getInInterceptorsForAssertion(WRONG_ASSERTION).isEmpty());
control.verify();
}
Class: org.apache.cxf.ws.policy.PolicyInterceptorsTest InternalCallVerifier IdentityVerifier
@Test public void testServerPolicyOutFaultInterceptorGetBindingFaultInfo(){
ServerPolicyOutFaultInterceptor interceptor=new ServerPolicyOutFaultInterceptor();
message=control.createMock(Message.class);
Exception ex=new UnsupportedOperationException(new RuntimeException());
boi=control.createMock(BindingOperationInfo.class);
EasyMock.expect(message.get(BindingFaultInfo.class)).andReturn(null);
BindingFaultInfo bfi=control.createMock(BindingFaultInfo.class);
Collection bfis=CastUtils.cast(Collections.EMPTY_LIST);
EasyMock.expect(boi.getFaults()).andReturn(bfis);
BindingOperationInfo wrappedBoi=control.createMock(BindingOperationInfo.class);
EasyMock.expect(boi.getWrappedOperation()).andReturn(wrappedBoi).times(2);
Collection wrappedBfis=CastUtils.cast(Collections.singletonList(bfi));
EasyMock.expect(wrappedBoi.getFaults()).andReturn(wrappedBfis);
FaultInfo fi=control.createMock(FaultInfo.class);
EasyMock.expect(bfi.getFaultInfo()).andReturn(fi);
EasyMock.expect(fi.getProperty(Class.class.getName(),Class.class)).andReturn(RuntimeException.class);
message.put(BindingFaultInfo.class,bfi);
EasyMock.expectLastCall();
control.replay();
assertSame(bfi,interceptor.getBindingFaultInfo(message,ex,boi));
control.verify();
}
Class: org.apache.cxf.ws.policy.PolicyRegistryImplTest InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testAll(){
PolicyRegistryImpl reg=new PolicyRegistryImpl();
IMocksControl control=EasyMock.createNiceControl();
Policy policy=control.createMock(Policy.class);
String key="key";
assertNull(reg.lookup(key));
reg.register(key,policy);
assertSame(policy,reg.lookup(key));
reg.remove(key);
assertNull(reg.lookup(key));
}
Class: org.apache.cxf.ws.policy.attachment.external.DomainExpressionBuilderRegistryTest APIUtilityVerifier InternalCallVerifier IdentityVerifier
@Test public void testBuild(){
DomainExpressionBuilder builder=control.createMock(DomainExpressionBuilder.class);
Map builders=new HashMap();
QName qn=new QName("http://a.b.c","x");
builders.put(qn,builder);
DomainExpressionBuilderRegistry reg=new DomainExpressionBuilderRegistry(builders);
Element e=control.createMock(Element.class);
EasyMock.expect(e.getNamespaceURI()).andReturn("http://a.b.c");
EasyMock.expect(e.getLocalName()).andReturn("x");
DomainExpression de=control.createMock(DomainExpression.class);
EasyMock.expect(builder.build(e)).andReturn(de);
control.replay();
assertSame(de,reg.build(e));
control.verify();
}
Class: org.apache.cxf.ws.policy.attachment.external.EndpointReferenceDomainExpressionTest BooleanVerifier InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testEndpointReferenceDomainExpression(){
EndpointReferenceType epr=control.createMock(EndpointReferenceType.class);
EndpointReferenceDomainExpression eprde=new EndpointReferenceDomainExpression();
assertNull(eprde.getEndpointReference());
eprde.setEndpointReference(epr);
assertSame(epr,eprde.getEndpointReference());
si=control.createMock(ServiceInfo.class);
boi=control.createMock(BindingOperationInfo.class);
bmi=control.createMock(BindingMessageInfo.class);
bfi=control.createMock(BindingFaultInfo.class);
assertTrue(!eprde.appliesTo(si));
assertTrue(!eprde.appliesTo(boi));
assertTrue(!eprde.appliesTo(bmi));
assertTrue(!eprde.appliesTo(bfi));
EndpointInfo ei=control.createMock(EndpointInfo.class);
EasyMock.expect(ei.getAddress()).andReturn("http://localhost:8080/GreeterPort");
AttributedURIType auri=control.createMock(AttributedURIType.class);
EasyMock.expect(epr.getAddress()).andReturn(auri);
EasyMock.expect(auri.getValue()).andReturn("http://localhost:8080/Greeter");
control.replay();
assertTrue(!eprde.appliesTo(ei));
control.verify();
control.reset();
EasyMock.expect(ei.getAddress()).andReturn("http://localhost:8080/GreeterPort");
EasyMock.expect(epr.getAddress()).andReturn(auri);
EasyMock.expect(auri.getValue()).andReturn("http://localhost:8080/GreeterPort");
control.replay();
assertTrue(eprde.appliesTo(ei));
control.verify();
bfi=null;
bmi=null;
boi=null;
si=null;
}
Class: org.apache.cxf.ws.policy.attachment.external.ExternalAttachmentProviderTest BooleanVerifier InternalCallVerifier
@Test public void testReadDocumentAttachmentElementWithoutAppliesTo() throws MalformedURLException {
ExternalAttachmentProvider eap=new ExternalAttachmentProvider();
URL url=ExternalAttachmentProviderTest.class.getResource("resources/attachments2.xml");
String uri=url.toExternalForm();
eap.setLocation(new UrlResource(uri));
eap.readDocument();
assertTrue(eap.getAttachments().isEmpty());
}
InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testGetEffectiveMessagePolicy(){
ExternalAttachmentProvider eap=new ExternalAttachmentProvider();
BindingMessageInfo bmi=control.createMock(BindingMessageInfo.class);
setUpAttachment(bmi,false,eap);
control.replay();
assertNull(eap.getEffectivePolicy(bmi,null));
control.verify();
control.reset();
setUpAttachment(bmi,true,eap);
control.replay();
assertSame(assertion,eap.getEffectivePolicy(bmi,null).getAssertions().get(0));
control.verify();
}
BooleanVerifier InternalCallVerifier
@Test public void testReadDocumentWithoutAttachmentElements() throws MalformedURLException {
ExternalAttachmentProvider eap=new ExternalAttachmentProvider();
URL url=ExternalAttachmentProviderTest.class.getResource("resources/attachments1.xml");
String uri=url.toExternalForm();
eap.setLocation(new UrlResource(uri));
eap.readDocument();
assertTrue(eap.getAttachments().isEmpty());
}
InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testGetEffectiveFaultPolicy(){
ExternalAttachmentProvider eap=new ExternalAttachmentProvider();
BindingFaultInfo bfi=control.createMock(BindingFaultInfo.class);
setUpAttachment(bfi,false,eap);
control.replay();
assertNull(eap.getEffectivePolicy(bfi,null));
control.verify();
control.reset();
setUpAttachment(bfi,true,eap);
control.replay();
assertSame(assertion,eap.getEffectivePolicy(bfi,null).getAssertions().get(0));
control.verify();
}
InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testGetEffectiveServicePolicy(){
ExternalAttachmentProvider eap=new ExternalAttachmentProvider();
ServiceInfo si=control.createMock(ServiceInfo.class);
setUpAttachment(si,false,eap);
control.replay();
assertNull(eap.getEffectivePolicy(si,null));
control.verify();
control.reset();
setUpAttachment(si,true,eap);
control.replay();
assertSame(assertion,eap.getEffectivePolicy(si,null).getAssertions().get(0));
control.verify();
}
InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testGetEffectiveEndpointPolicy(){
ExternalAttachmentProvider eap=new ExternalAttachmentProvider();
EndpointInfo ei=control.createMock(EndpointInfo.class);
setUpAttachment(ei,false,eap);
control.replay();
assertNull(eap.getEffectivePolicy(ei,null));
control.verify();
control.reset();
setUpAttachment(ei,true,eap);
control.replay();
assertSame(assertion,eap.getEffectivePolicy(ei,null).getAssertions().get(0));
control.verify();
}
InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testGetEffectiveOperationPolicy(){
BindingOperationInfo boi=control.createMock(BindingOperationInfo.class);
ExternalAttachmentProvider eap=new ExternalAttachmentProvider();
setUpAttachment(boi,false,eap);
control.replay();
assertNull(eap.getEffectivePolicy(boi,null));
control.verify();
control.reset();
setUpAttachment(boi,true,eap);
control.replay();
assertSame(assertion,eap.getEffectivePolicy(boi,null).getAssertions().get(0));
control.verify();
}
InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testBasic(){
ExternalAttachmentProvider eap=new ExternalAttachmentProvider();
assertNull(eap.getLocation());
Resource uri=control.createMock(Resource.class);
eap.setLocation(uri);
assertSame(uri,eap.getLocation());
}
InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testReadDocumentEPRDomainExpression() throws MalformedURLException {
Bus bus=control.createMock(Bus.class);
DomainExpressionBuilderRegistry debr=control.createMock(DomainExpressionBuilderRegistry.class);
EasyMock.expect(bus.getExtension(DomainExpressionBuilderRegistry.class)).andReturn(debr);
DomainExpression de=control.createMock(DomainExpression.class);
EasyMock.expect(debr.build(EasyMock.isA(Element.class))).andReturn(de);
PolicyBuilder pb=control.createMock(PolicyBuilder.class);
EasyMock.expect(bus.getExtension(PolicyBuilder.class)).andReturn(pb).anyTimes();
Policy p=control.createMock(Policy.class);
EasyMock.expect(pb.getPolicy(EasyMock.isA(Element.class))).andReturn(p);
control.replay();
ExternalAttachmentProvider eap=new ExternalAttachmentProvider(bus);
URL url=ExternalAttachmentProviderTest.class.getResource("resources/attachments4.xml");
String uri=url.toExternalForm();
eap.setLocation(new UrlResource(uri));
eap.readDocument();
assertEquals(1,eap.getAttachments().size());
PolicyAttachment pa=eap.getAttachments().iterator().next();
assertSame(p,pa.getPolicy());
assertEquals(1,pa.getDomainExpressions().size());
assertSame(de,pa.getDomainExpressions().iterator().next());
control.verify();
}
Class: org.apache.cxf.ws.policy.attachment.external.PolicyAttachmentTest BooleanVerifier InternalCallVerifier
@Test public void testAppliesToFault(){
BindingFaultInfo bfi1=control.createMock(BindingFaultInfo.class);
BindingFaultInfo bfi2=control.createMock(BindingFaultInfo.class);
DomainExpression de=control.createMock(DomainExpression.class);
Collection des=Collections.singletonList(de);
PolicyAttachment pa=new PolicyAttachment();
pa.setDomainExpressions(des);
EasyMock.expect(de.appliesTo(bfi1)).andReturn(false);
EasyMock.expect(de.appliesTo(bfi2)).andReturn(true);
control.replay();
assertTrue(!pa.appliesTo(bfi1));
assertTrue(pa.appliesTo(bfi2));
control.verify();
}
BooleanVerifier InternalCallVerifier
@Test public void testAppliesToService(){
ServiceInfo si1=control.createMock(ServiceInfo.class);
ServiceInfo si2=control.createMock(ServiceInfo.class);
DomainExpression de=control.createMock(DomainExpression.class);
Collection des=Collections.singletonList(de);
PolicyAttachment pa=new PolicyAttachment();
pa.setDomainExpressions(des);
EasyMock.expect(de.appliesTo(si1)).andReturn(false);
EasyMock.expect(de.appliesTo(si2)).andReturn(true);
control.replay();
assertTrue(!pa.appliesTo(si1));
assertTrue(pa.appliesTo(si2));
control.verify();
}
BooleanVerifier InternalCallVerifier
@Test public void testAppliesToMessage(){
BindingMessageInfo bmi1=control.createMock(BindingMessageInfo.class);
BindingMessageInfo bmi2=control.createMock(BindingMessageInfo.class);
DomainExpression de=control.createMock(DomainExpression.class);
Collection des=Collections.singletonList(de);
PolicyAttachment pa=new PolicyAttachment();
pa.setDomainExpressions(des);
EasyMock.expect(de.appliesTo(bmi1)).andReturn(false);
EasyMock.expect(de.appliesTo(bmi2)).andReturn(true);
control.replay();
assertTrue(!pa.appliesTo(bmi1));
assertTrue(pa.appliesTo(bmi2));
control.verify();
}
BooleanVerifier InternalCallVerifier
@Test public void testAppliesToOperation(){
BindingOperationInfo boi1=control.createMock(BindingOperationInfo.class);
BindingOperationInfo boi2=control.createMock(BindingOperationInfo.class);
DomainExpression de=control.createMock(DomainExpression.class);
Collection des=Collections.singletonList(de);
PolicyAttachment pa=new PolicyAttachment();
pa.setDomainExpressions(des);
EasyMock.expect(de.appliesTo(boi1)).andReturn(false);
EasyMock.expect(de.appliesTo(boi2)).andReturn(true);
control.replay();
assertTrue(!pa.appliesTo(boi1));
assertTrue(pa.appliesTo(boi2));
control.verify();
}
BooleanVerifier InternalCallVerifier
@Test public void testAppliesToEndpoint(){
EndpointInfo ei1=control.createMock(EndpointInfo.class);
EndpointInfo ei2=control.createMock(EndpointInfo.class);
DomainExpression de=control.createMock(DomainExpression.class);
Collection des=Collections.singletonList(de);
PolicyAttachment pa=new PolicyAttachment();
pa.setDomainExpressions(des);
EasyMock.expect(de.appliesTo(ei1)).andReturn(false);
EasyMock.expect(de.appliesTo(ei2)).andReturn(true);
control.replay();
assertTrue(!pa.appliesTo(ei1));
assertTrue(pa.appliesTo(ei2));
control.verify();
}
InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testBasic(){
PolicyAttachment pa=new PolicyAttachment();
assertNull(pa.getDomainExpressions());
assertNull(pa.getPolicy());
Policy p=control.createMock(Policy.class);
Collection des=CastUtils.cast(Collections.emptyList(),DomainExpression.class);
pa.setPolicy(p);
pa.setDomainExpressions(des);
assertSame(p,pa.getPolicy());
assertSame(des,pa.getDomainExpressions());
}
Class: org.apache.cxf.ws.policy.attachment.reference.ReferenceResolverTest InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testLocalServiceModelReferenceResolver(){
DescriptionInfo di=control.createMock(DescriptionInfo.class);
PolicyBuilder builder=control.createMock(PolicyBuilder.class);
LocalServiceModelReferenceResolver resolver=new LocalServiceModelReferenceResolver(di,builder);
List extensions=new ArrayList();
EasyMock.expect(di.getExtensors(UnknownExtensibilityElement.class)).andReturn(extensions);
control.replay();
assertNull(resolver.resolveReference("A"));
control.verify();
control.reset();
UnknownExtensibilityElement extension=control.createMock(UnknownExtensibilityElement.class);
extensions.add(extension);
EasyMock.expect(di.getExtensors(UnknownExtensibilityElement.class)).andReturn(extensions);
Element e=control.createMock(Element.class);
EasyMock.expect(extension.getElement()).andReturn(e).times(2);
QName qn=new QName(Constants.URI_POLICY_NS,Constants.ELEM_POLICY);
EasyMock.expect(extension.getElementType()).andReturn(qn).anyTimes();
EasyMock.expect(e.getAttributeNS(PolicyConstants.WSU_NAMESPACE_URI,PolicyConstants.WSU_ID_ATTR_NAME)).andReturn("A");
Policy p=control.createMock(Policy.class);
EasyMock.expect(builder.getPolicy(e)).andReturn(p);
control.replay();
assertSame(p,resolver.resolveReference("A"));
control.verify();
}
Class: org.apache.cxf.ws.policy.attachment.wsdl11.Wsdl11AttachmentPolicyProviderTest UtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testEffectiveServicePolicies() throws WSDLException {
Policy p;
Policy ep;
ep=app.getEffectivePolicy(services[0],null);
assertTrue(ep == null || ep.isEmpty());
p=app.getElementPolicy(services[0]);
assertTrue(p == null || p.isEmpty());
ep=app.getEffectivePolicy(services[1],null);
assertTrue(ep == null || ep.isEmpty());
try {
ep=app.getEffectivePolicy(services[2],null);
fail("Expected PolicyException not thrown.");
}
catch ( PolicyException ex) {
}
ep=app.getEffectivePolicy(services[3],null);
assertNotNull(ep);
assertTrue(!ep.isEmpty());
verifyAssertionsOnly(ep,2);
p=app.getElementPolicy(services[3]);
assertTrue(PolicyComparator.compare(p,ep));
ep=app.getEffectivePolicy(services[4],null);
assertNotNull(ep);
assertTrue(!ep.isEmpty());
verifyAssertionsOnly(ep,3);
p=app.getElementPolicy(services[4]);
assertTrue(PolicyComparator.compare(p,ep));
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testEffectiveBindingOperationPolicies(){
Policy ep;
ep=app.getEffectivePolicy(getBindingOperationInfo(endpoints[0]),null);
assertTrue(ep == null || ep.isEmpty());
ep=app.getEffectivePolicy(getBindingOperationInfo(endpoints[9]),null);
assertNotNull(ep);
assertTrue(!ep.isEmpty());
verifyAssertionsOnly(ep,1);
ep=app.getEffectivePolicy(getBindingOperationInfo(endpoints[10]),null);
assertNotNull(ep);
assertTrue(!ep.isEmpty());
verifyAssertionsOnly(ep,2);
ep=app.getEffectivePolicy(getBindingOperationInfo(endpoints[11]),null);
assertNotNull(ep);
assertTrue(!ep.isEmpty());
verifyAssertionsOnly(ep,3);
}
BooleanVerifier InternalCallVerifier
@Test public void testEffectiveMessagePolicies(){
Policy ep;
ep=app.getEffectivePolicy(getBindingMessageInfo(endpoints[0],true),null);
assertTrue(ep == null || ep.isEmpty());
ep=app.getEffectivePolicy(getBindingMessageInfo(endpoints[12],true),null);
assertTrue(!ep.isEmpty());
verifyAssertionsOnly(ep,1);
ep=app.getEffectivePolicy(getBindingMessageInfo(endpoints[13],true),null);
assertTrue(!ep.isEmpty());
verifyAssertionsOnly(ep,1);
ep=app.getEffectivePolicy(getBindingMessageInfo(endpoints[14],true),null);
assertTrue(!ep.isEmpty());
verifyAssertionsOnly(ep,1);
ep=app.getEffectivePolicy(getBindingMessageInfo(endpoints[15],true),null);
assertTrue(!ep.isEmpty());
verifyAssertionsOnly(ep,3);
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testEffectiveEndpointPolicies(){
Policy ep;
Policy p;
ep=app.getEffectivePolicy(endpoints[0],null);
assertTrue(ep == null || ep.isEmpty());
ep=app.getEffectivePolicy(endpoints[5],null);
assertNotNull(ep);
assertTrue(!ep.isEmpty());
verifyAssertionsOnly(ep,1);
p=app.getElementPolicy(endpoints[5]);
assertTrue(PolicyComparator.compare(p,ep));
ep=app.getEffectivePolicy(endpoints[6],null);
assertNotNull(ep);
assertTrue(!ep.isEmpty());
verifyAssertionsOnly(ep,1);
p=app.getElementPolicy(endpoints[6].getBinding());
assertTrue(PolicyComparator.compare(p,ep));
ep=app.getEffectivePolicy(endpoints[7],null);
assertNotNull(ep);
assertTrue(!ep.isEmpty());
verifyAssertionsOnly(ep,1);
p=app.getElementPolicy(endpoints[7].getInterface());
assertTrue(PolicyComparator.compare(p,ep));
ep=app.getEffectivePolicy(endpoints[8],null);
assertNotNull(ep);
assertTrue(!ep.isEmpty());
verifyAssertionsOnly(ep,3);
ep=app.getEffectivePolicy(endpoints[18],null);
assertNotNull(ep);
assertTrue(!ep.isEmpty());
verifyAssertionsOnly(ep,2);
}
UtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testElementPolicies() throws WSDLException {
Policy p;
p=app.getElementPolicy(services[0]);
assertTrue(p == null || p.isEmpty());
p=app.getElementPolicy(services[1]);
assertTrue(p == null || p.isEmpty());
try {
p=app.getElementPolicy(services[2]);
fail("Expected PolicyException not thrown.");
}
catch ( PolicyException ex) {
}
p=app.getElementPolicy(services[3]);
assertNotNull(p);
assertTrue(!p.isEmpty());
verifyAssertionsOnly(p,2);
p=app.getElementPolicy(services[4]);
assertNotNull(p);
assertTrue(!p.isEmpty());
verifyAssertionsOnly(p,3);
EndpointInfo ei=new EndpointInfo();
assertTrue(app.getElementPolicy(ei) == null);
}
UtilityVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testResolveLocal(){
Policy ep;
ep=app.getElementPolicy(services[16]);
assertNotNull(ep);
verifyAssertionsOnly(ep,2);
try {
app.getElementPolicy(endpoints[16]);
fail("Expected PolicyException not thrown.");
}
catch ( PolicyException ex) {
}
}
Class: org.apache.cxf.ws.policy.blueprint.PolicyBPHandlerTest InternalCallVerifier NullVerifier
@Test public void testGetSchemaLocation(){
PolicyBPHandler handler=new PolicyBPHandler();
assertNotNull(handler.getSchemaLocation("http://cxf.apache.org/policy"));
assertNotNull(handler.getSchemaLocation("http://www.w3.org/ns/ws-policy"));
assertNotNull(handler.getSchemaLocation("http://www.w3.org/2006/07/ws-policy"));
assertNotNull(handler.getSchemaLocation("http://schemas.xmlsoap.org/ws/2004/09/policy"));
assertNotNull(handler.getSchemaLocation("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"));
assertNotNull(handler.getSchemaLocation("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"));
assertNotNull(handler.getSchemaLocation("http://www.w3.org/2000/09/xmldsig#"));
assertNotNull(handler.getSchemaLocation("http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702"));
}
Class: org.apache.cxf.ws.policy.builder.jaxb.JaxbAssertionBuilderTest InternalCallVerifier IdentityVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetKnownElements() throws Exception {
QName qn=new QName("http://cxf.apache.org/test/assertions/foo","FooType");
JaxbAssertionBuilder ab=new JaxbAssertionBuilder(FooType.class,qn);
assertNotNull(ab);
assertEquals(1,ab.getKnownElements().length);
assertSame(qn,ab.getKnownElements()[0]);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBuild() throws Exception {
QName qn=new QName("http://cxf.apache.org/test/assertions/foo","FooType");
JaxbAssertionBuilder ab=new JaxbAssertionBuilder(FooType.class,qn);
assertNotNull(ab);
InputStream is=JaxbAssertionBuilderTest.class.getResourceAsStream("foo.xml");
Document doc=StaxUtils.read(is);
Element elem=DOMUtils.findAllElementsByTagNameNS(doc.getDocumentElement(),"http://cxf.apache.org/test/assertions/foo","foo").get(0);
Assertion a=ab.build(elem,null);
JaxbAssertion jba=JaxbAssertion.cast(a,FooType.class);
FooType foo=jba.getData();
assertEquals("CXF",foo.getName());
assertEquals(2,foo.getNumber().intValue());
}
Class: org.apache.cxf.ws.policy.builder.jaxb.JaxbAssertionTest BooleanVerifier InternalCallVerifier IdentityVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBasic(){
JaxbAssertion assertion=new JaxbAssertion();
assertNull(assertion.getName());
assertNull(assertion.getData());
assertTrue(!assertion.isOptional());
assertEquals(Constants.TYPE_ASSERTION,assertion.getType());
FooType data=new FooType();
data.setName("CXF");
data.setNumber(2);
QName qn=new QName("http://cxf.apache.org/test/assertions/foo","FooType");
assertion.setName(qn);
assertion.setData(data);
assertion.setOptional(true);
assertSame(qn,assertion.getName());
assertSame(data,assertion.getData());
assertTrue(assertion.isOptional());
assertEquals(Constants.TYPE_ASSERTION,assertion.getType());
}
BooleanVerifier InternalCallVerifier
@Test public void testEqual(){
JaxbAssertion assertion=new JaxbAssertion();
FooType data=new FooType();
data.setName("CXF");
data.setNumber(2);
QName qn=new QName("http://cxf.apache.org/test/assertions/foo","FooType");
assertion.setName(qn);
assertion.setData(data);
PolicyComponent pc=new Policy();
assertTrue(!assertion.equal(pc));
pc=new All();
assertTrue(!assertion.equal(pc));
pc=new ExactlyOne();
assertTrue(!assertion.equal(pc));
IMocksControl ctrl=EasyMock.createNiceControl();
PrimitiveAssertion xpa=ctrl.createMock(PrimitiveAssertion.class);
QName oqn=new QName("http://cxf.apache.org/test/assertions/blah","OtherType");
EasyMock.expect(xpa.getName()).andReturn(oqn);
EasyMock.expect(xpa.getType()).andReturn(Constants.TYPE_ASSERTION);
ctrl.replay();
assertTrue(!assertion.equal(xpa));
ctrl.verify();
FooType odata=new FooType();
odata.setName(data.getName());
odata.setNumber(data.getNumber());
JaxbAssertion oassertion=new JaxbAssertion();
oassertion.setData(odata);
oassertion.setName(qn);
assertTrue(!assertion.equal(oassertion));
oassertion.setData(data);
assertTrue(assertion.equal(oassertion));
assertTrue(assertion.equal(assertion));
}
APIUtilityVerifier IterativeVerifier BranchVerifier BooleanVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testNormalise(){
JaxbAssertion assertion=new JaxbAssertion();
FooType data=new FooType();
data.setName("CXF");
data.setNumber(2);
QName qn=new QName("http://cxf.apache.org/test/assertions/foo","FooType");
assertion.setName(qn);
assertion.setData(data);
JaxbAssertion> normalised=(JaxbAssertion>)assertion.normalize();
assertTrue(normalised.equal(assertion));
assertSame(assertion.getData(),normalised.getData());
assertion.setOptional(true);
PolicyComponent pc=assertion.normalize();
assertEquals(Constants.TYPE_POLICY,pc.getType());
Policy p=(Policy)pc;
Iterator> alternatives=p.getAlternatives();
int total=0;
for (int i=0; i < 2; i++) {
List pcs=alternatives.next();
if (!pcs.isEmpty()) {
assertTrue(assertion.equal(pcs.get(0)));
total+=pcs.size();
}
}
assertTrue(!alternatives.hasNext());
assertEquals(1,total);
}
Class: org.apache.cxf.ws.policy.selector.FirstAlternativeSelectorTest InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testChooseAlternative(){
AlternativeSelector selector=new FirstAlternativeSelector();
PolicyEngine engine=control.createMock(PolicyEngine.class);
Assertor assertor=control.createMock(Assertor.class);
Policy policy=new Policy();
ExactlyOne ea=new ExactlyOne();
All all=new All();
PolicyAssertion a1=new TestAssertion();
all.addAssertion(a1);
ea.addPolicyComponent(all);
Collection firstAlternative=CastUtils.cast(all.getPolicyComponents(),PolicyAssertion.class);
policy.addPolicyComponent(ea);
Message m=new MessageImpl();
EasyMock.expect(engine.supportsAlternative(firstAlternative,assertor,m)).andReturn(false);
control.replay();
assertNull(selector.selectAlternative(policy,engine,assertor,null,m));
control.verify();
control.reset();
EasyMock.expect(engine.supportsAlternative(firstAlternative,assertor,m)).andReturn(true);
control.replay();
Collection chosen=selector.selectAlternative(policy,engine,assertor,null,m);
assertSame(1,chosen.size());
assertSame(chosen.size(),firstAlternative.size());
assertSame(chosen.iterator().next(),firstAlternative.iterator().next());
control.verify();
control.reset();
All other=new All();
other.addAssertion(a1);
ea.addPolicyComponent(other);
Collection secondAlternative=CastUtils.cast(other.getPolicyComponents(),PolicyAssertion.class);
EasyMock.expect(engine.supportsAlternative(firstAlternative,assertor,m)).andReturn(false);
EasyMock.expect(engine.supportsAlternative(secondAlternative,assertor,m)).andReturn(true);
control.replay();
chosen=selector.selectAlternative(policy,engine,assertor,null,m);
assertSame(1,chosen.size());
assertSame(chosen.size(),secondAlternative.size());
assertSame(chosen.iterator().next(),secondAlternative.iterator().next());
control.verify();
}
Class: org.apache.cxf.ws.policy.selector.MinimalMaximalAlternativeSelectorTest InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testChooseMaxAlternative(){
Message m=new MessageImpl();
AlternativeSelector selector=new MaximalAlternativeSelector();
PolicyEngine engine=control.createMock(PolicyEngine.class);
Assertor assertor=control.createMock(Assertor.class);
Policy policy=new Policy();
ExactlyOne ea=new ExactlyOne();
All all=new All();
PolicyAssertion a1=new TestAssertion();
all.addAssertion(a1);
ea.addPolicyComponent(all);
Collection maxAlternative=CastUtils.cast(all.getPolicyComponents(),PolicyAssertion.class);
all=new All();
ea.addPolicyComponent(all);
Collection minAlternative=CastUtils.cast(all.getPolicyComponents(),PolicyAssertion.class);
policy.addPolicyComponent(ea);
EasyMock.expect(engine.supportsAlternative(maxAlternative,assertor,m)).andReturn(true);
EasyMock.expect(engine.supportsAlternative(minAlternative,assertor,m)).andReturn(true);
control.replay();
Collection choice=selector.selectAlternative(policy,engine,assertor,null,m);
assertEquals(1,choice.size());
assertSame(a1,choice.iterator().next());
control.verify();
}
InternalCallVerifier EqualityVerifier
@Test public void testChooseMinAlternative(){
Message m=new MessageImpl();
AlternativeSelector selector=new MinimalAlternativeSelector();
PolicyEngine engine=control.createMock(PolicyEngine.class);
Assertor assertor=control.createMock(Assertor.class);
Policy policy=new Policy();
ExactlyOne ea=new ExactlyOne();
All all=new All();
PolicyAssertion a1=new TestAssertion();
all.addAssertion(a1);
ea.addPolicyComponent(all);
Collection maxAlternative=CastUtils.cast(all.getPolicyComponents(),PolicyAssertion.class);
all=new All();
ea.addPolicyComponent(all);
Collection minAlternative=CastUtils.cast(all.getPolicyComponents(),PolicyAssertion.class);
policy.addPolicyComponent(ea);
EasyMock.expect(engine.supportsAlternative(maxAlternative,assertor,m)).andReturn(true);
EasyMock.expect(engine.supportsAlternative(minAlternative,assertor,m)).andReturn(true);
control.replay();
Collection choice=selector.selectAlternative(policy,engine,assertor,null,m);
assertEquals(0,choice.size());
control.verify();
}
Class: org.apache.cxf.ws.policy.spring.PolicyBeansTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testParse(){
Bus bus=new SpringBusFactory().createBus("org/apache/cxf/ws/policy/spring/beans.xml");
try {
PolicyEngine pe=bus.getExtension(PolicyEngine.class);
assertTrue("Policy engine is not enabled",pe.isEnabled());
assertTrue("Unknown assertions are not ignored",pe.isIgnoreUnknownAssertions());
assertEquals(MaximalAlternativeSelector.class.getName(),pe.getAlternativeSelector().getClass().getName());
PolicyEngineImpl pei=(PolicyEngineImpl)pe;
Collection providers=pei.getPolicyProviders();
assertEquals(4,providers.size());
int n=0;
for ( PolicyProvider pp : providers) {
if (pp instanceof ExternalAttachmentProvider) {
n++;
}
}
assertEquals("Unexpected number of external providers",2,n);
}
finally {
bus.shutdown(true);
}
}
Class: org.apache.cxf.ws.rm.AbstractEndpointTest InternalCallVerifier IdentityVerifier
@Test public void testGenerateSequenceIdentifier(){
RMManager mgr=control.createMock(RMManager.class);
EasyMock.expect(rme.getManager()).andReturn(mgr);
SequenceIdentifierGenerator generator=control.createMock(SequenceIdentifierGenerator.class);
EasyMock.expect(mgr.getIdGenerator()).andReturn(generator);
Identifier id=control.createMock(Identifier.class);
EasyMock.expect(generator.generateSequenceIdentifier()).andReturn(id);
control.replay();
AbstractEndpoint tested=new AbstractEndpoint(rme);
assertSame(id,tested.generateSequenceIdentifier());
control.verify();
}
InternalCallVerifier IdentityVerifier
@Test public void testAccessors(){
Endpoint ae=control.createMock(Endpoint.class);
EasyMock.expect(rme.getApplicationEndpoint()).andReturn(ae);
RMManager mgr=control.createMock(RMManager.class);
EasyMock.expect(rme.getManager()).andReturn(mgr);
control.replay();
AbstractEndpoint tested=new AbstractEndpoint(rme);
assertSame(rme,tested.getReliableEndpoint());
assertSame(ae,tested.getEndpoint());
assertSame(mgr,tested.getManager());
}
Class: org.apache.cxf.ws.rm.AbstractRMInterceptorTest BooleanVerifier InternalCallVerifier
@Test public void testAssertReliability(){
RMInterceptor interceptor=new RMInterceptor();
Message message=control.createMock(Message.class);
EasyMock.expect(message.get(AssertionInfoMap.class)).andReturn(null);
AssertionInfoMap aim=control.createMock(AssertionInfoMap.class);
Collection ais=new ArrayList();
EasyMock.expect(message.get(AssertionInfoMap.class)).andReturn(aim).times(2);
PolicyAssertion a=control.createMock(PolicyAssertion.class);
AssertionInfo ai=new AssertionInfo(a);
EasyMock.expectLastCall();
control.replay();
interceptor.assertReliability(message);
assertTrue(!ai.isAsserted());
aim.put(RM10Constants.RMASSERTION_QNAME,ais);
interceptor.assertReliability(message);
assertTrue(!ai.isAsserted());
ais.add(ai);
interceptor.assertReliability(message);
}
UtilityVerifier InternalCallVerifier IdentityVerifier HybridVerifier
@Test public void testHandleMessageSequenceFault(){
RMInterceptor interceptor=new RMInterceptor();
Message message=control.createMock(Message.class);
SequenceFault sf=control.createMock(SequenceFault.class);
interceptor.setSequenceFault(sf);
Exchange ex=control.createMock(Exchange.class);
EasyMock.expect(message.getExchange()).andReturn(ex).anyTimes();
Endpoint e=control.createMock(Endpoint.class);
EasyMock.expect(ex.getEndpoint()).andReturn(e);
Binding b=control.createMock(Binding.class);
EasyMock.expect(e.getBinding()).andReturn(b);
RMManager mgr=control.createMock(RMManager.class);
interceptor.setManager(mgr);
BindingFaultFactory bff=control.createMock(BindingFaultFactory.class);
EasyMock.expect(mgr.getBindingFaultFactory(b)).andReturn(bff);
Fault fault=control.createMock(Fault.class);
EasyMock.expect(bff.createFault(sf,message)).andReturn(fault);
EasyMock.expect(bff.toString(fault)).andReturn("f");
control.replay();
try {
interceptor.handleMessage(message);
fail("Expected Fault not thrown.");
}
catch ( Fault f) {
assertSame(f,fault);
}
}
UtilityVerifier InternalCallVerifier IdentityVerifier HybridVerifier
@Test public void testHandleMessageRMException(){
RMInterceptor interceptor=new RMInterceptor();
Message message=control.createMock(Message.class);
RMException rme=control.createMock(RMException.class);
interceptor.setRMException(rme);
control.replay();
try {
interceptor.handleMessage(message);
fail("Expected Fault not thrown.");
}
catch ( Fault f) {
assertSame(rme,f.getCause());
}
}
InternalCallVerifier IdentityVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testAccessors(){
RMInterceptor interceptor=new RMInterceptor();
assertEquals(Phase.PRE_LOGICAL,interceptor.getPhase());
Bus bus=control.createMock(Bus.class);
RMManager busMgr=control.createMock(RMManager.class);
EasyMock.expect(bus.getExtension(RMManager.class)).andReturn(busMgr);
RMManager mgr=control.createMock(RMManager.class);
control.replay();
assertNull(interceptor.getBus());
interceptor.setBus(bus);
assertSame(bus,interceptor.getBus());
assertSame(busMgr,interceptor.getManager());
interceptor.setManager(mgr);
assertSame(mgr,interceptor.getManager());
}
UtilityVerifier InternalCallVerifier IdentityVerifier HybridVerifier
@Test public void testHandleMessageSequenceFaultNoBinding(){
RMInterceptor interceptor=new RMInterceptor();
Message message=control.createMock(Message.class);
SequenceFault sf=control.createMock(SequenceFault.class);
interceptor.setSequenceFault(sf);
Exchange ex=control.createMock(Exchange.class);
EasyMock.expect(message.getExchange()).andReturn(ex).anyTimes();
Endpoint e=control.createMock(Endpoint.class);
EasyMock.expect(ex.getEndpoint()).andReturn(e);
EasyMock.expect(e.getBinding()).andReturn(null);
control.replay();
try {
interceptor.handleMessage(message);
fail("Expected Fault not thrown.");
}
catch ( Fault f) {
assertSame(sf,f.getCause());
}
}
Class: org.apache.cxf.ws.rm.AbstractSequenceTest BooleanVerifier InternalCallVerifier
@Test public void testIdentifierEquals(){
Identifier id1=null;
Identifier id2=null;
assertTrue(AbstractSequence.identifierEquals(id1,id2));
ObjectFactory factory=new ObjectFactory();
id1=factory.createIdentifier();
id1.setValue("seq1");
assertTrue(!AbstractSequence.identifierEquals(id1,id2));
id2=factory.createIdentifier();
id2.setValue("seq2");
assertTrue(!AbstractSequence.identifierEquals(id1,id2));
id2.setValue("seq1");
assertTrue(AbstractSequence.identifierEquals(id1,id2));
}
Class: org.apache.cxf.ws.rm.DestinationSequenceTest InternalCallVerifier IdentityVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testConstructors(){
Identifier otherId=factory.createIdentifier();
otherId.setValue("otherSeq");
DestinationSequence seq=new DestinationSequence(id,ref,destination,ProtocolVariation.RM10WSA200408);
assertEquals(id,seq.getIdentifier());
assertEquals(0,seq.getLastMessageNumber());
assertSame(ref,seq.getAcksTo());
assertNotNull(seq.getAcknowledgment());
assertNotNull(seq.getMonitor());
SequenceAcknowledgement ack=new SequenceAcknowledgement();
seq=new DestinationSequence(id,ref,10,ack,ProtocolVariation.RM10WSA200408);
assertEquals(id,seq.getIdentifier());
assertEquals(10,seq.getLastMessageNumber());
assertSame(ref,seq.getAcksTo());
assertSame(ack,seq.getAcknowledgment());
assertNotNull(seq.getMonitor());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testMerge(){
DestinationSequence seq=new DestinationSequence(id,ref,destination,ProtocolVariation.RM10WSA200408);
List ranges=seq.getAcknowledgment().getAcknowledgementRange();
AcknowledgementRange r;
for (int i=0; i < 5; i++) {
r=new AcknowledgementRange();
r.setLower(new Long(3 * i + 1));
r.setUpper(new Long(3 * i + 3));
ranges.add(r);
}
seq.mergeRanges();
assertEquals(1,ranges.size());
r=ranges.get(0);
assertEquals(new Long(1),r.getLower());
assertEquals(new Long(15),r.getUpper());
ranges.clear();
for (int i=0; i < 5; i++) {
r=new AcknowledgementRange();
r.setLower(new Long(3 * i + 1));
r.setUpper(new Long(3 * i + 2));
ranges.add(r);
}
seq.mergeRanges();
assertEquals(5,ranges.size());
ranges.clear();
for (int i=0; i < 5; i++) {
if (i != 2) {
r=new AcknowledgementRange();
r.setLower(new Long(3 * i + 1));
r.setUpper(new Long(3 * i + 3));
ranges.add(r);
}
}
seq.mergeRanges();
assertEquals(2,ranges.size());
r=ranges.get(0);
assertEquals(new Long(1),r.getLower());
assertEquals(new Long(6),r.getUpper());
r=ranges.get(1);
assertEquals(new Long(10),r.getLower());
assertEquals(new Long(15),r.getUpper());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCorrelationID(){
setUpDestination();
DestinationSequence seq=new DestinationSequence(id,ref,destination,ProtocolVariation.RM10WSA200408);
String correlationID="abdc1234";
assertNull("unexpected correlation ID",seq.getCorrelationID());
seq.setCorrelationID(correlationID);
assertEquals("unexpected correlation ID",correlationID,seq.getCorrelationID());
}
InternalCallVerifier IdentityVerifier
@Test public void testGetSetDestination(){
control.replay();
DestinationSequence seq=new DestinationSequence(id,ref,destination,ProtocolVariation.RM10WSA200408);
seq.setDestination(destination);
assertSame(destination,seq.getDestination());
}
BooleanVerifier InternalCallVerifier
@Test public void testAcknowledgeImmediate() throws SequenceFault {
Timer timer=control.createMock(Timer.class);
setUpDestination(timer,null);
Message message=setUpMessage("1");
control.replay();
DestinationSequence seq=new DestinationSequence(id,ref,destination,ProtocolVariation.RM10WSA200408);
assertTrue(!seq.sendAcknowledgement());
seq.acknowledge(message);
assertTrue(seq.sendAcknowledgement());
seq.acknowledgmentSent();
assertFalse(seq.sendAcknowledgement());
control.verify();
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testMonitor() throws SequenceFault {
Timer timer=control.createMock(Timer.class);
setUpDestination(timer,null);
Message[] messages=new Message[15];
for (int i=0; i < messages.length; i++) {
messages[i]=setUpMessage(Integer.toString(i + 1));
}
control.replay();
DestinationSequence seq=new DestinationSequence(id,ref,destination,ProtocolVariation.RM10WSA200408);
SequenceMonitor monitor=seq.getMonitor();
assertNotNull(monitor);
monitor.setMonitorInterval(500);
assertEquals(0,monitor.getMPM());
for (int i=0; i < 10; i++) {
seq.acknowledge(messages[i]);
try {
Thread.sleep(55);
}
catch ( InterruptedException ex) {
}
}
int mpm1=monitor.getMPM();
assertTrue("unexpected MPM: " + mpm1,mpm1 > 0);
for (int i=10; i < messages.length; i++) {
seq.acknowledge(messages[i]);
try {
Thread.sleep(110);
}
catch ( InterruptedException ex) {
}
}
int mpm2=monitor.getMPM();
assertTrue(mpm2 > 0);
assertTrue(mpm1 > mpm2);
control.verify();
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testAcknowledgeAppendRange() throws SequenceFault {
Timer timer=control.createMock(Timer.class);
setUpDestination(timer,null);
Message[] messages=new Message[]{setUpMessage("1"),setUpMessage("2"),setUpMessage("5"),setUpMessage("4"),setUpMessage("6")};
control.replay();
DestinationSequence seq=new DestinationSequence(id,ref,destination,ProtocolVariation.RM10WSA200408);
List ranges=seq.getAcknowledgment().getAcknowledgementRange();
for (int i=0; i < messages.length; i++) {
seq.acknowledge(messages[i]);
}
assertEquals(2,ranges.size());
AcknowledgementRange r=ranges.get(0);
assertEquals(1,r.getLower().intValue());
assertEquals(2,r.getUpper().intValue());
r=ranges.get(1);
assertEquals(4,r.getLower().intValue());
assertEquals(6,r.getUpper().intValue());
control.verify();
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testAcknowledgeBasic() throws SequenceFault {
Timer timer=control.createMock(Timer.class);
setUpDestination(timer,null);
Message message1=setUpMessage("1");
Message message2=setUpMessage("2");
control.replay();
DestinationSequence seq=new DestinationSequence(id,ref,destination,ProtocolVariation.RM10WSA200408);
List ranges=seq.getAcknowledgment().getAcknowledgementRange();
assertEquals(0,ranges.size());
seq.acknowledge(message1);
assertEquals(1,ranges.size());
AcknowledgementRange r1=ranges.get(0);
assertEquals(1,r1.getLower().intValue());
assertEquals(1,r1.getUpper().intValue());
seq.acknowledge(message2);
assertEquals(1,ranges.size());
r1=ranges.get(0);
assertEquals(1,r1.getLower().intValue());
assertEquals(2,r1.getUpper().intValue());
control.verify();
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testAcknowledgeInsertRange() throws SequenceFault {
Timer timer=control.createMock(Timer.class);
setUpDestination(timer,null);
Message[] messages=new Message[]{setUpMessage("1"),setUpMessage("2"),setUpMessage("9"),setUpMessage("10"),setUpMessage("4"),setUpMessage("9"),setUpMessage("2")};
control.replay();
DestinationSequence seq=new DestinationSequence(id,ref,destination,ProtocolVariation.RM10WSA200408);
List ranges=seq.getAcknowledgment().getAcknowledgementRange();
for (int i=0; i < messages.length; i++) {
seq.acknowledge(messages[i]);
}
assertEquals(3,ranges.size());
AcknowledgementRange r=ranges.get(0);
assertEquals(1,r.getLower().intValue());
assertEquals(2,r.getUpper().intValue());
r=ranges.get(1);
assertEquals(4,r.getLower().intValue());
assertEquals(4,r.getUpper().intValue());
r=ranges.get(2);
assertEquals(9,r.getLower().intValue());
assertEquals(10,r.getUpper().intValue());
control.verify();
}
InternalCallVerifier EqualityVerifier
@Test public void testGetEndpointIdentifier(){
setUpDestination();
String name="abc";
EasyMock.expect(destination.getName()).andReturn(name);
control.replay();
DestinationSequence seq=new DestinationSequence(id,ref,destination,ProtocolVariation.RM10WSA200408);
assertEquals("Unexpected endpoint identifier",name,seq.getEndpointIdentifier());
control.verify();
}
BooleanVerifier InternalCallVerifier
@Test public void testAcknowledgeDeferred() throws SequenceFault, RMException {
Timer timer=new Timer();
RMEndpoint rme=control.createMock(RMEndpoint.class);
setUpDestination(timer,rme);
DestinationSequence seq=new DestinationSequence(id,ref,destination,ProtocolVariation.RM10WSA200408);
Proxy proxy=control.createMock(Proxy.class);
EasyMock.expect(rme.getProxy()).andReturn(proxy).anyTimes();
proxy.acknowledge(seq);
EasyMock.expectLastCall();
Message[] messages=new Message[]{setUpMessage("1"),setUpMessage("2"),setUpMessage("3")};
control.replay();
ap.setIntraMessageThreshold(0);
config.setAcknowledgementInterval(new Long(200));
assertTrue(!seq.sendAcknowledgement());
for (int i=0; i < messages.length; i++) {
seq.acknowledge(messages[i]);
}
assertFalse(seq.sendAcknowledgement());
try {
Thread.sleep(250);
}
catch ( InterruptedException ex) {
}
assertTrue(seq.sendAcknowledgement());
seq.acknowledgmentSent();
assertFalse(seq.sendAcknowledgement());
control.verify();
}
BooleanVerifier InternalCallVerifier
@Test public void testCanPiggybackAckOnPartialResponse(){
DestinationSequence seq=new DestinationSequence(id,ref,destination,ProtocolVariation.RM10WSA200408);
AttributedURIType uri=control.createMock(AttributedURIType.class);
EasyMock.expect(ref.getAddress()).andReturn(uri);
String addr="http://localhost:9999/reponses";
EasyMock.expect(uri.getValue()).andReturn(addr);
control.replay();
assertTrue(!seq.canPiggybackAckOnPartialResponse());
control.verify();
control.reset();
EasyMock.expect(ref.getAddress()).andReturn(uri);
EasyMock.expect(uri.getValue()).andReturn(Names.WSA_ANONYMOUS_ADDRESS);
control.replay();
assertTrue(seq.canPiggybackAckOnPartialResponse());
control.verify();
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testEqualsAndHashCode(){
DestinationSequence seq=new DestinationSequence(id,ref,destination,ProtocolVariation.RM10WSA200408);
DestinationSequence otherSeq=null;
assertTrue(!seq.equals(otherSeq));
otherSeq=new DestinationSequence(id,ref,destination,ProtocolVariation.RM10WSA200408);
assertEquals(seq,otherSeq);
assertEquals(seq.hashCode(),otherSeq.hashCode());
Identifier otherId=factory.createIdentifier();
otherId.setValue("otherSeq");
otherSeq=new DestinationSequence(otherId,ref,destination,ProtocolVariation.RM10WSA200408);
assertTrue(!seq.equals(otherSeq));
assertTrue(seq.hashCode() != otherSeq.hashCode());
assertTrue(!seq.equals(this));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testAcknowledgePrependRange() throws SequenceFault {
Timer timer=control.createMock(Timer.class);
setUpDestination(timer,null);
Message[] messages=new Message[]{setUpMessage("4"),setUpMessage("5"),setUpMessage("6"),setUpMessage("4"),setUpMessage("2"),setUpMessage("2")};
control.replay();
DestinationSequence seq=new DestinationSequence(id,ref,destination,ProtocolVariation.RM10WSA200408);
List ranges=seq.getAcknowledgment().getAcknowledgementRange();
for (int i=0; i < messages.length; i++) {
seq.acknowledge(messages[i]);
}
assertEquals(2,ranges.size());
AcknowledgementRange r=ranges.get(0);
assertEquals(2,r.getLower().intValue());
assertEquals(2,r.getUpper().intValue());
r=ranges.get(1);
assertEquals(4,r.getLower().intValue());
assertEquals(6,r.getUpper().intValue());
control.verify();
}
Class: org.apache.cxf.ws.rm.DestinationTest InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testAddRemoveSequence(){
DestinationSequence ds=control.createMock(DestinationSequence.class);
ds.setDestination(destination);
EasyMock.expectLastCall();
Identifier id=control.createMock(Identifier.class);
EasyMock.expect(ds.getIdentifier()).andReturn(id).times(3);
String sid="s1";
EasyMock.expect(id.getValue()).andReturn(sid).times(3);
RMManager manager=control.createMock(RMManager.class);
EasyMock.expect(rme.getManager()).andReturn(manager).times(2);
RMStore store=control.createMock(RMStore.class);
EasyMock.expect(manager.getStore()).andReturn(store).times(2);
store.createDestinationSequence(ds);
EasyMock.expectLastCall();
store.removeDestinationSequence(id);
EasyMock.expectLastCall();
control.replay();
destination.addSequence(ds);
assertEquals(1,destination.getAllSequences().size());
assertSame(ds,destination.getSequence(id));
destination.removeSequence(ds);
assertEquals(0,destination.getAllSequences().size());
}
InternalCallVerifier NullVerifier
@Test public void testGetSequence(){
Identifier id=control.createMock(Identifier.class);
String sid="s1";
EasyMock.expect(id.getValue()).andReturn(sid);
control.replay();
assertNull(destination.getSequence(id));
}
Class: org.apache.cxf.ws.rm.ManagedRMManagerTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testGetSourceSequenceAcknowledgedRange() throws Exception {
ManagedRMEndpoint managedEndpoint=createTestManagedRMEndpoint();
Long[] ranges=managedEndpoint.getSourceSequenceAcknowledgedRange("seq1");
assertEquals(4,ranges.length);
assertTrue(1L == ranges[0] && 1L == ranges[1] && 3L == ranges[2] && 3L == ranges[3]);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testGetUnAcknowledgedMessageIdentifiers() throws Exception {
ManagedRMEndpoint managedEndpoint=createTestManagedRMEndpoint();
Long[] numbers=managedEndpoint.getUnAcknowledgedMessageIdentifiers("seq1");
assertEquals(2,numbers.length);
assertTrue(2L == numbers[0] && 4L == numbers[1]);
}
InternalCallVerifier EqualityVerifier
@Test public void testManagedRMEndpointGetQueuedCount() throws Exception {
ManagedRMEndpoint managedEndpoint=createTestManagedRMEndpoint();
int n=managedEndpoint.getQueuedMessageTotalCount(true);
assertEquals(3,n);
n=managedEndpoint.getQueuedMessageCount("seq1",true);
assertEquals(2,n);
}
BooleanVerifier InternalCallVerifier
@Test public void testSuspendAndResumeSourceQueue() throws Exception {
ManagedRMEndpoint managedEndpoint=createTestManagedRMEndpoint();
TestRetransmissionQueue rq=(TestRetransmissionQueue)manager.getRetransmissionQueue();
assertFalse(rq.isSuspended("seq1"));
managedEndpoint.suspendSourceQueue("seq1");
assertTrue(rq.isSuspended("seq1"));
managedEndpoint.resumeSourceQueue("seq1");
assertFalse(rq.isSuspended("seq1"));
}
UtilityVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testRemoveSequence() throws Exception {
manager=new RMManager();
RMEndpoint rme=control.createMock(RMEndpoint.class);
EndpointReferenceType ref=RMUtils.createReference(TEST_URI);
Source source=new Source(rme);
Destination destination=new Destination(rme);
RetransmissionQueue rq=new TestRetransmissionQueue();
manager.setRetransmissionQueue(rq);
manager.initialise();
SourceSequence ss1=createTestSourceSequence(source,"seq1",ref,ProtocolVariation.RM10WSA200408,new long[]{1L,1L,3L,3L});
SourceSequence ss3=createTestSourceSequence(source,"seq3",ref,ProtocolVariation.RM10WSA200408,new long[]{1L,5L});
EasyMock.expect(rme.getManager()).andReturn(manager).anyTimes();
EasyMock.expect(rme.getSource()).andReturn(source).anyTimes();
EasyMock.expect(rme.getDestination()).andReturn(destination).anyTimes();
control.replay();
setCurrentMessageNumber(ss1,5L);
setCurrentMessageNumber(ss3,5L);
source.addSequence(ss1);
source.addSequence(ss3);
source.setCurrent(ss3);
ManagedRMEndpoint managedEndpoint=new ManagedRMEndpoint(rme);
CompositeData cd=managedEndpoint.getSourceSequence("seq3");
assertNotNull(cd);
managedEndpoint.removeSourceSequence("seq3");
try {
cd=managedEndpoint.getSourceSequence("seq3");
fail("sequnce not removed");
}
catch ( Exception e) {
}
cd=managedEndpoint.getSourceSequence("seq1");
assertNotNull(cd);
try {
managedEndpoint.removeSourceSequence("seq1");
fail("sequnce may not be removed");
}
catch ( Exception e) {
}
cd=managedEndpoint.getSourceSequence("seq1");
assertNotNull(cd);
managedEndpoint.purgeUnAcknowledgedMessages("seq1");
managedEndpoint.removeSourceSequence("seq1");
try {
cd=managedEndpoint.getSourceSequence("seq1");
fail("sequnce not removed");
}
catch ( Exception e) {
}
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testManagedRMManager() throws Exception {
final SpringBusFactory factory=new SpringBusFactory();
bus=factory.createBus("org/apache/cxf/ws/rm/managed-manager-bean.xml");
im=bus.getExtension(InstrumentationManager.class);
manager=bus.getExtension(RMManager.class);
endpoint=createTestEndpoint();
assertTrue("Instrumentation Manager should not be null",im != null);
assertTrue("RMManager should not be null",manager != null);
MBeanServer mbs=im.getMBeanServer();
assertNotNull("MBeanServer should be available.",mbs);
ObjectName managerName=RMUtils.getManagedObjectName(manager);
Set mbset=mbs.queryMBeans(managerName,null);
assertEquals("ManagedRMManager should be found",1,mbset.size());
Object o;
o=mbs.getAttribute(managerName,"UsingStore");
assertTrue(o instanceof Boolean);
assertFalse("Store attribute is false",(Boolean)o);
o=mbs.invoke(managerName,"getEndpointIdentifiers",null,null);
assertTrue(o instanceof String[]);
assertEquals("No Endpoint",0,((String[])o).length);
RMEndpoint rme=createTestRMEndpoint();
ObjectName endpointName=RMUtils.getManagedObjectName(rme);
mbset=mbs.queryMBeans(endpointName,null);
assertEquals("ManagedRMEndpoint should be found",1,mbset.size());
o=mbs.invoke(managerName,"getEndpointIdentifiers",null,null);
assertEquals("One Endpoint",1,((String[])o).length);
assertEquals("Endpoint identifier must match",RMUtils.getEndpointIdentifier(endpoint,bus),((String[])o)[0]);
o=mbs.getAttribute(endpointName,"Address");
assertTrue(o instanceof String);
assertEquals("Endpoint address must match",TEST_URI,o);
o=mbs.getAttribute(endpointName,"LastApplicationMessage");
assertNull(o);
o=mbs.getAttribute(endpointName,"LastControlMessage");
assertNull(o);
o=mbs.invoke(endpointName,"getDestinationSequenceIds",null,null);
assertTrue(o instanceof String[]);
assertEquals("No sequence",0,((String[])o).length);
o=mbs.invoke(endpointName,"getDestinationSequences",null,null);
assertTrue(o instanceof CompositeData[]);
assertEquals("No sequence",0,((CompositeData[])o).length);
o=mbs.invoke(endpointName,"getSourceSequenceIds",new Object[]{true},new String[]{"boolean"});
assertTrue(o instanceof String[]);
assertEquals("No sequence",0,((String[])o).length);
o=mbs.invoke(endpointName,"getSourceSequences",new Object[]{true},new String[]{"boolean"});
assertTrue(o instanceof CompositeData[]);
assertEquals("No sequence",0,((CompositeData[])o).length);
o=mbs.invoke(endpointName,"getDeferredAcknowledgementTotalCount",null,null);
assertTrue(o instanceof Integer);
assertEquals("No deferred acks",0,o);
o=mbs.invoke(endpointName,"getQueuedMessageTotalCount",new Object[]{true},new String[]{"boolean"});
assertTrue(o instanceof Integer);
assertEquals("No queued messages",0,o);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testGetDestinationSequences() throws Exception {
ManagedRMEndpoint managedEndpoint=createTestManagedRMEndpoint();
String[] sids=managedEndpoint.getDestinationSequenceIds();
assertEquals(2,sids.length);
assertTrue(("seq3".equals(sids[0]) || "seq3".equals(sids[1])) && ("seq4".equals(sids[0]) || "seq4".equals(sids[1])));
CompositeData[] sequences=managedEndpoint.getDestinationSequences();
assertEquals(2,sequences.length);
verifyDestinationSequence(sequences[0]);
verifyDestinationSequence(sequences[1]);
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testGetSourceSequences() throws Exception {
ManagedRMEndpoint managedEndpoint=createTestManagedRMEndpoint();
String[] sids=managedEndpoint.getSourceSequenceIds(true);
assertEquals(2,sids.length);
assertTrue(("seq1".equals(sids[0]) || "seq1".equals(sids[1])) && ("seq2".equals(sids[0]) || "seq2".equals(sids[1])));
String sid=managedEndpoint.getCurrentSourceSequenceId();
assertEquals("seq2",sid);
CompositeData[] sequences=managedEndpoint.getSourceSequences(true);
assertEquals(2,sequences.length);
verifySourceSequence(sequences[0]);
verifySourceSequence(sequences[1]);
}
InternalCallVerifier NullVerifier
@Test public void testGetRetransmissionStatus() throws Exception {
ManagedRMEndpoint managedEndpoint=createTestManagedRMEndpoint();
TestRetransmissionQueue rq=(TestRetransmissionQueue)manager.getRetransmissionQueue();
CompositeData status=managedEndpoint.getRetransmissionStatus("seq1",3L);
assertNull(status);
status=managedEndpoint.getRetransmissionStatus("seq1",2L);
assertNotNull(status);
verifyRetransmissionStatus(status,2L,rq.getRetransmissionStatus());
}
Class: org.apache.cxf.ws.rm.MessageCountingCallbackTest UtilityVerifier BooleanVerifier InternalCallVerifier HybridVerifier
@Test public void test(){
final MessageCountingCallback ccb=new MessageCountingCallback();
ccb.messageAccepted("123",1);
assertFalse(ccb.waitComplete(1));
Thread thread=new Thread(new Runnable(){
@Override public void run(){
assertTrue(ccb.waitComplete(1000));
}
}
);
try {
Thread.sleep(20);
}
catch ( InterruptedException e) {
}
ccb.messageAcknowledged("123",1);
try {
thread.join(100);
}
catch ( InterruptedException e) {
fail("Thread did not complete");
}
}
Class: org.apache.cxf.ws.rm.ProxyTest InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testOfferedIdentifier(){
OfferType offer=control.createMock(OfferType.class);
Identifier id=control.createMock(Identifier.class);
EasyMock.expect(offer.getIdentifier()).andReturn(id).anyTimes();
control.replay();
Proxy proxy=new Proxy(rme);
assertNull(proxy.getOfferedIdentifier());
proxy.setOfferedIdentifier(offer);
assertSame(id,proxy.getOfferedIdentifier());
}
InternalCallVerifier NullVerifier
@Test public void testRMClientConstruction(){
Proxy proxy=new Proxy(rme);
Bus bus=control.createMock(Bus.class);
Endpoint endpoint=control.createMock(Endpoint.class);
Conduit conduit=control.createMock(Conduit.class);
org.apache.cxf.ws.addressing.EndpointReferenceType address=control.createMock(org.apache.cxf.ws.addressing.EndpointReferenceType.class);
control.replay();
assertNotNull(proxy.createClient(bus,endpoint,ProtocolVariation.RM10WSA200408,conduit,address));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testInvoke() throws Exception {
Method m=Proxy.class.getDeclaredMethod("createClient",new Class[]{Bus.class,Endpoint.class,ProtocolVariation.class,Conduit.class,org.apache.cxf.ws.addressing.EndpointReferenceType.class});
Proxy proxy=EasyMock.createMockBuilder(Proxy.class).addMockedMethod(m).createMock(control);
proxy.setReliableEndpoint(rme);
RMManager manager=control.createMock(RMManager.class);
EasyMock.expect(rme.getManager()).andReturn(manager).anyTimes();
Bus bus=control.createMock(Bus.class);
EasyMock.expect(manager.getBus()).andReturn(bus).anyTimes();
Endpoint endpoint=control.createMock(Endpoint.class);
EasyMock.expect(rme.getEndpoint(ProtocolVariation.RM10WSA200408)).andReturn(endpoint).anyTimes();
BindingInfo bi=control.createMock(BindingInfo.class);
EasyMock.expect(rme.getBindingInfo(ProtocolVariation.RM10WSA200408)).andReturn(bi).anyTimes();
Conduit conduit=control.createMock(Conduit.class);
EasyMock.expect(rme.getConduit()).andReturn(conduit).anyTimes();
org.apache.cxf.ws.addressing.EndpointReferenceType replyTo=control.createMock(org.apache.cxf.ws.addressing.EndpointReferenceType.class);
EasyMock.expect(rme.getReplyTo()).andReturn(replyTo).anyTimes();
OperationInfo oi=control.createMock(OperationInfo.class);
BindingOperationInfo boi=control.createMock(BindingOperationInfo.class);
EasyMock.expect(bi.getOperation(oi)).andReturn(boi).anyTimes();
Client client=control.createMock(Client.class);
EasyMock.expect(client.getRequestContext()).andReturn(new HashMap()).anyTimes();
EasyMock.expect(proxy.createClient(bus,endpoint,ProtocolVariation.RM10WSA200408,conduit,replyTo)).andReturn(client).anyTimes();
Object[] args=new Object[]{};
Map context=new HashMap();
Object[] results=new Object[]{"a","b","c"};
Exchange exchange=control.createMock(Exchange.class);
EasyMock.expect(client.invoke(boi,args,context,exchange)).andReturn(results).anyTimes();
control.replay();
assertEquals("a",proxy.invoke(oi,ProtocolVariation.RM10WSA200408,args,context,exchange));
}
InternalCallVerifier IdentityVerifier
@Test public void testRMClientGetConduit(){
Proxy proxy=new Proxy(rme);
Bus bus=control.createMock(Bus.class);
Endpoint endpoint=control.createMock(Endpoint.class);
Conduit conduit=control.createMock(Conduit.class);
ConduitSelector cs=control.createMock(ConduitSelector.class);
EasyMock.expect(cs.selectConduit(EasyMock.isA(Message.class))).andReturn(conduit).anyTimes();
control.replay();
Proxy.RMClient client=proxy.new RMClient(bus,endpoint,cs);
assertSame(conduit,client.getConduit());
}
Class: org.apache.cxf.ws.rm.RMContextUtilsTest InternalCallVerifier IdentityVerifier
@Test public void testRetrieveOutboundRMProperties(){
Message msg=control.createMock(Message.class);
RMProperties rmps=control.createMock(RMProperties.class);
EasyMock.expect(msg.get(RMMessageConstants.RM_PROPERTIES_OUTBOUND)).andReturn(rmps);
control.replay();
assertSame(rmps,RMContextUtils.retrieveRMProperties(msg,true));
}
InternalCallVerifier IdentityVerifier
@Test public void testRetrieveInboundRMPropertiesFromInboundMessage(){
Message inMsg=control.createMock(Message.class);
Exchange ex=control.createMock(Exchange.class);
EasyMock.expect(inMsg.getExchange()).andReturn(ex);
EasyMock.expect(ex.getOutMessage()).andReturn(null);
EasyMock.expect(ex.getOutFaultMessage()).andReturn(null);
RMProperties rmps=control.createMock(RMProperties.class);
EasyMock.expect(inMsg.get(RMMessageConstants.RM_PROPERTIES_INBOUND)).andReturn(rmps);
control.replay();
assertSame(rmps,RMContextUtils.retrieveRMProperties(inMsg,false));
}
InternalCallVerifier IdentityVerifier
@Test public void testRetrieveInboundRMPropertiesFromOutboundMessage(){
Message outMsg=control.createMock(Message.class);
Exchange ex=control.createMock(Exchange.class);
EasyMock.expect(outMsg.getExchange()).andReturn(ex).times(3);
EasyMock.expect(ex.getOutMessage()).andReturn(outMsg);
Message inMsg=control.createMock(Message.class);
EasyMock.expect(ex.getInMessage()).andReturn(null);
EasyMock.expect(ex.getInFaultMessage()).andReturn(inMsg);
RMProperties rmps=control.createMock(RMProperties.class);
EasyMock.expect(inMsg.get(RMMessageConstants.RM_PROPERTIES_INBOUND)).andReturn(rmps);
control.replay();
assertSame(rmps,RMContextUtils.retrieveRMProperties(outMsg,false));
}
BooleanVerifier InternalCallVerifier
@Test public void testIsServerSide(){
Message msg=control.createMock(Message.class);
Exchange ex=control.createMock(Exchange.class);
EasyMock.expect(msg.getExchange()).andReturn(ex);
EasyMock.expect(ex.getDestination()).andReturn(null);
control.replay();
assertTrue(!RMContextUtils.isServerSide(msg));
}
InternalCallVerifier IdentityVerifier
@Test public void testRetrieveMAPs(){
Message msg=control.createMock(Message.class);
EasyMock.expect(msg.get(Message.REQUESTOR_ROLE)).andReturn(Boolean.TRUE);
AddressingProperties maps=control.createMock(AddressingProperties.class);
EasyMock.expect(msg.get(JAXWSAConstants.ADDRESSING_PROPERTIES_OUTBOUND)).andReturn(maps);
control.replay();
assertSame(maps,RMContextUtils.retrieveMAPs(msg,false,true));
}
Class: org.apache.cxf.ws.rm.RMEndpointTest InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testGetUsingAddressing(){
EndpointInfo ei=null;
control.replay();
assertNull(rme.getUsingAddressing(ei));
control.verify();
control.reset();
ExtensibilityElement ua=control.createMock(ExtensibilityElement.class);
ei=control.createMock(EndpointInfo.class);
List noExts=new ArrayList();
List exts=new ArrayList();
exts.add(ua);
EasyMock.expect(ei.getExtensors(ExtensibilityElement.class)).andReturn(noExts);
BindingInfo bi=control.createMock(BindingInfo.class);
EasyMock.expect(ei.getBinding()).andReturn(bi).times(2);
EasyMock.expect(bi.getExtensors(ExtensibilityElement.class)).andReturn(noExts);
ServiceInfo si=control.createMock(ServiceInfo.class);
EasyMock.expect(ei.getService()).andReturn(si).times(2);
EasyMock.expect(si.getExtensors(ExtensibilityElement.class)).andReturn(exts);
EasyMock.expect(ua.getElementType()).andReturn(Names.WSAW_USING_ADDRESSING_QNAME);
control.replay();
assertSame(ua,rme.getUsingAddressing(ei));
}
InternalCallVerifier IdentityVerifier
@Test public void testGetSetSource(){
Source s=control.createMock(Source.class);
control.replay();
assertSame(rme,rme.getSource().getReliableEndpoint());
rme.setSource(s);
assertSame(s,rme.getSource());
}
InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testCreateService(){
Service as=control.createMock(Service.class);
EasyMock.expect(ae.getService()).andReturn(as);
control.replay();
rme.createServices();
Service s=rme.getService(ProtocolVariation.RM10WSA200408);
assertNotNull(s);
WrappedService ws=(WrappedService)s;
assertSame(as,ws.getWrappedService());
assertSame(rme.getServant(),s.getInvoker());
verifyService();
}
InternalCallVerifier NullVerifier
@Test public void testConstructor(){
control.replay();
assertNotNull(rme);
assertNull(rme.getEndpoint(ProtocolVariation.RM10WSA200408));
assertNull(rme.getService(ProtocolVariation.RM10WSA200408));
assertNull(rme.getConduit());
assertNull(rme.getReplyTo());
}
InternalCallVerifier IdentityVerifier
@Test public void testGetSetDestination(){
Destination d=control.createMock(Destination.class);
control.replay();
assertSame(rme,rme.getDestination().getReliableEndpoint());
rme.setDestination(d);
assertSame(d,rme.getDestination());
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testMessageArrivals(){
assertEquals(0L,rme.getLastApplicationMessage());
assertEquals(0L,rme.getLastControlMessage());
rme.receivedControlMessage();
assertEquals(0L,rme.getLastApplicationMessage());
assertTrue(rme.getLastControlMessage() > 0);
rme.receivedApplicationMessage();
assertTrue(rme.getLastApplicationMessage() > 0);
assertTrue(rme.getLastControlMessage() > 0);
control.replay();
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testCreateEndpoint() throws NoSuchMethodException, EndpointException {
Method m=RMEndpoint.class.getDeclaredMethod("getUsingAddressing",new Class[]{EndpointInfo.class});
Service as=control.createMock(Service.class);
EndpointInfo aei=new EndpointInfo();
ae=new EndpointImpl(null,as,aei);
rme=EasyMock.createMockBuilder(RMEndpoint.class).withConstructor(manager,ae).addMockedMethod(m).createMock(control);
rme.setAplicationEndpoint(ae);
rme.setManager(manager);
SoapBindingInfo bi=control.createMock(SoapBindingInfo.class);
aei.setBinding(bi);
SoapVersion sv=Soap11.getInstance();
EasyMock.expect(bi.getSoapVersion()).andReturn(sv);
String ns="http://schemas.xmlsoap.org/wsdl/soap/";
EasyMock.expect(bi.getBindingId()).andReturn(ns);
aei.setTransportId(ns);
String addr="addr";
aei.setAddress(addr);
Object ua=new Object();
EasyMock.expect(rme.getUsingAddressing(aei)).andReturn(ua);
control.replay();
rme.createServices();
rme.createEndpoints(null);
Endpoint e=rme.getEndpoint(ProtocolVariation.RM10WSA200408);
WrappedEndpoint we=(WrappedEndpoint)e;
assertSame(ae,we.getWrappedEndpoint());
Service s=rme.getService(ProtocolVariation.RM10WSA200408);
assertEquals(1,s.getEndpoints().size());
assertSame(e,s.getEndpoints().get(RM10Constants.PORT_NAME));
}
InternalCallVerifier IdentityVerifier
@Test public void testGetUsingAddressingFromExtensions(){
List exts=new ArrayList();
ExtensibilityElement ua=control.createMock(ExtensibilityElement.class);
exts.add(ua);
EasyMock.expect(ua.getElementType()).andReturn(Names.WSAW_USING_ADDRESSING_QNAME);
control.replay();
assertSame(ua,rme.getUsingAddressing(exts));
}
APIUtilityVerifier InternalCallVerifier IdentityVerifier
@Test public void testInitialise() throws NoSuchMethodException {
Message m=new MessageImpl();
Method m1=RMEndpoint.class.getDeclaredMethod("createServices",new Class[]{});
Method m2=RMEndpoint.class.getDeclaredMethod("createEndpoints",new Class[]{org.apache.cxf.transport.Destination.class});
Method m3=RMEndpoint.class.getDeclaredMethod("setPolicies",new Class[]{Message.class});
rme=EasyMock.createMockBuilder(RMEndpoint.class).addMockedMethods(m1,m2,m3).createMock(control);
rme.createServices();
EasyMock.expectLastCall();
rme.createEndpoints(null);
EasyMock.expectLastCall();
rme.setPolicies(m);
EasyMock.expectLastCall();
Conduit c=control.createMock(Conduit.class);
EndpointReferenceType epr=control.createMock(EndpointReferenceType.class);
control.replay();
rme.initialise(new RMConfiguration(),c,epr,null,m);
assertSame(c,rme.getConduit());
assertSame(epr,rme.getReplyTo());
}
Class: org.apache.cxf.ws.rm.RMInInterceptorTest InternalCallVerifier IdentityVerifier
@Test public void testOrdering(){
control.replay();
Phase p=new Phase(Phase.PRE_LOGICAL,1);
SortedSet phases=new TreeSet();
phases.add(p);
PhaseInterceptorChain chain=new PhaseInterceptorChain(phases);
MAPAggregator map=new MAPAggregator();
RMInInterceptor rmi=new RMInInterceptor();
chain.add(rmi);
chain.add(map);
Iterator> it=chain.iterator();
assertSame("Unexpected order.",rmi,it.next());
assertSame("Unexpected order.",map,it.next());
}
Class: org.apache.cxf.ws.rm.RMManagerConfigurationTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testExactlyOnce(){
SpringBusFactory factory=new SpringBusFactory();
bus=factory.createBus("org/apache/cxf/ws/rm/exactly-once.xml",false);
RMManager manager=bus.getExtension(RMManager.class);
RMConfiguration cfg=manager.getConfiguration();
DeliveryAssurance da=cfg.getDeliveryAssurance();
assertEquals(da,DeliveryAssurance.EXACTLY_ONCE);
assertFalse(cfg.isInOrder());
}
Class: org.apache.cxf.ws.rm.RMManagerTest InternalCallVerifier IdentityVerifier
@Test public void testGetReliableEndpointServerSideCreate() throws NoSuchMethodException, RMException {
Method m1=RMManager.class.getDeclaredMethod("createReliableEndpoint",new Class[]{Endpoint.class});
manager=control.createMock(RMManager.class,new Method[]{m1});
manager.setReliableEndpointsMap(new HashMap());
Message message=control.createMock(Message.class);
Exchange exchange=control.createMock(Exchange.class);
EasyMock.expect(message.getExchange()).andReturn(exchange).anyTimes();
WrappedEndpoint wre=control.createMock(WrappedEndpoint.class);
EasyMock.expect(exchange.getEndpoint()).andReturn(wre).anyTimes();
EndpointInfo ei=control.createMock(EndpointInfo.class);
EasyMock.expect(wre.getEndpointInfo()).andReturn(ei).anyTimes();
QName name=RM10Constants.PORT_NAME;
EasyMock.expect(ei.getName()).andReturn(name).anyTimes();
Endpoint e=control.createMock(Endpoint.class);
EasyMock.expect(wre.getWrappedEndpoint()).andReturn(e).anyTimes();
RMEndpoint rme=control.createMock(RMEndpoint.class);
EasyMock.expect(manager.createReliableEndpoint(e)).andReturn(rme).anyTimes();
org.apache.cxf.transport.Destination destination=control.createMock(org.apache.cxf.transport.Destination.class);
EasyMock.expect(exchange.getDestination()).andReturn(destination).anyTimes();
AddressingProperties maps=control.createMock(AddressingProperties.class);
EasyMock.expect(message.get(Message.REQUESTOR_ROLE)).andReturn(null);
EasyMock.expect(message.get(JAXWSAConstants.ADDRESSING_PROPERTIES_INBOUND)).andReturn(maps).anyTimes();
EndpointReferenceType replyTo=RMUtils.createAnonymousReference();
EasyMock.expect(maps.getReplyTo()).andReturn(replyTo).anyTimes();
EasyMock.expect(exchange.getConduit(message)).andReturn(null).anyTimes();
rme.initialise(manager.getConfiguration(),null,replyTo,null,message);
EasyMock.expectLastCall();
control.replay();
assertSame(rme,manager.getReliableEndpoint(message));
control.verify();
control.reset();
EasyMock.expect(message.getExchange()).andReturn(exchange);
EasyMock.expect(exchange.getEndpoint()).andReturn(wre);
EasyMock.expect(wre.getEndpointInfo()).andReturn(ei);
EasyMock.expect(ei.getName()).andReturn(name);
EasyMock.expect(wre.getWrappedEndpoint()).andReturn(e);
control.replay();
assertSame(rme,manager.getReliableEndpoint(message));
control.verify();
}
UtilityVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testShutdown(){
Bus bus=new SpringBusFactory().createBus("org/apache/cxf/ws/rm/rmmanager.xml",false);
manager=bus.getExtension(RMManager.class);
Endpoint e=control.createMock(Endpoint.class);
RMEndpoint rme=control.createMock(RMEndpoint.class);
manager.getReliableEndpointsMap().put(e,rme);
manager.getTimer();
rme.shutdown();
EasyMock.expectLastCall();
assertNotNull(manager);
class TestTask extends TimerTask {
public void run(){
}
}
control.replay();
bus.shutdown(true);
try {
manager.getTimer().schedule(new TestTask(),5000);
fail("Timer has not been cancelled.");
}
catch ( IllegalStateException ex) {
}
control.verify();
}
InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testGetDestination() throws NoSuchMethodException, RMException {
Method m=RMManager.class.getDeclaredMethod("getReliableEndpoint",new Class[]{Message.class});
manager=control.createMock(RMManager.class,new Method[]{m});
Message message=control.createMock(Message.class);
RMEndpoint rme=control.createMock(RMEndpoint.class);
EasyMock.expect(manager.getReliableEndpoint(message)).andReturn(rme);
Destination destination=control.createMock(Destination.class);
EasyMock.expect(rme.getDestination()).andReturn(destination);
control.replay();
assertSame(destination,manager.getDestination(message));
control.verify();
control.reset();
EasyMock.expect(manager.getReliableEndpoint(message)).andReturn(null);
control.replay();
assertNull(manager.getDestination(message));
control.verify();
}
InternalCallVerifier IdentityVerifier
@Test public void testGetReliableEndpointExisting() throws NoSuchMethodException, RMException {
Method m1=RMManager.class.getDeclaredMethod("createReliableEndpoint",new Class[]{Endpoint.class});
manager=control.createMock(RMManager.class,new Method[]{m1});
manager.setReliableEndpointsMap(new HashMap());
Message message=control.createMock(Message.class);
RMConfiguration config=new RMConfiguration();
config.setRMNamespace(RM10Constants.NAMESPACE_URI);
config.setRM10AddressingNamespace(RM10Constants.NAMESPACE_URI);
EasyMock.expect(manager.getEffectiveConfiguration(message)).andReturn(config).anyTimes();
Exchange exchange=control.createMock(Exchange.class);
EasyMock.expect(message.getExchange()).andReturn(exchange);
Endpoint endpoint=control.createMock(Endpoint.class);
EasyMock.expect(exchange.getEndpoint()).andReturn(endpoint);
EndpointInfo ei=control.createMock(EndpointInfo.class);
EasyMock.expect(endpoint.getEndpointInfo()).andReturn(ei);
QName name=new QName("http://x.y.z/a","GreeterPort");
EasyMock.expect(ei.getName()).andReturn(name);
RMEndpoint rme=control.createMock(RMEndpoint.class);
manager.getReliableEndpointsMap().put(endpoint,rme);
control.replay();
assertSame(rme,manager.getReliableEndpoint(message));
control.verify();
}
InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testAccessors(){
manager=new RMManager();
assertNull(manager.getBus());
assertNull(manager.getStore());
assertNull(manager.getRetransmissionQueue());
assertNotNull(manager.getTimer());
Bus bus=control.createMock(Bus.class);
RMStore store=control.createMock(RMStore.class);
RetransmissionQueue queue=control.createMock(RetransmissionQueue.class);
manager.setBus(bus);
manager.setStore(store);
manager.setRetransmissionQueue(queue);
assertSame(bus,manager.getBus());
assertSame(store,manager.getStore());
assertSame(queue,manager.getRetransmissionQueue());
control.replay();
control.reset();
}
InternalCallVerifier IdentityVerifier
@Test public void testGetExistingSequence() throws NoSuchMethodException, SequenceFault, RMException {
Method m=RMManager.class.getDeclaredMethod("getSource",new Class[]{Message.class});
manager=control.createMock(RMManager.class,new Method[]{m});
Message message=control.createMock(Message.class);
Identifier inSid=control.createMock(Identifier.class);
Source source=control.createMock(Source.class);
EasyMock.expect(manager.getSource(message)).andReturn(source);
SourceSequence sseq=control.createMock(SourceSequence.class);
EasyMock.expect(source.getCurrent(inSid)).andReturn(sseq);
control.replay();
assertSame(sseq,manager.getSequence(inSid,message,null));
control.verify();
}
InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testRecoverReliableClientEndpoint() throws NoSuchMethodException {
Method method=RMManager.class.getDeclaredMethod("createReliableEndpoint",new Class[]{Endpoint.class});
manager=control.createMock(RMManager.class,new Method[]{method});
manager.setReliableEndpointsMap(new HashMap());
Endpoint endpoint=control.createMock(Endpoint.class);
EndpointInfo ei=control.createMock(EndpointInfo.class);
ServiceInfo si=control.createMock(ServiceInfo.class);
BindingInfo bi=control.createMock(BindingInfo.class);
InterfaceInfo ii=control.createMock(InterfaceInfo.class);
setUpEndpointForRecovery(endpoint,ei,si,bi,ii);
Conduit conduit=control.createMock(Conduit.class);
setUpRecoverReliableEndpoint(endpoint,conduit,null,null,null,null);
control.replay();
manager.recoverReliableEndpoint(endpoint,conduit);
control.verify();
control.reset();
setUpEndpointForRecovery(endpoint,ei,si,bi,ii);
SourceSequence ss=control.createMock(SourceSequence.class);
DestinationSequence ds=control.createMock(DestinationSequence.class);
setUpRecoverReliableEndpoint(endpoint,conduit,ss,ds,null,null);
control.replay();
manager.recoverReliableEndpoint(endpoint,conduit);
control.verify();
control.reset();
setUpEndpointForRecovery(endpoint,ei,si,bi,ii);
RMMessage m=control.createMock(RMMessage.class);
Capture mc=Capture.newInstance();
setUpRecoverReliableEndpoint(endpoint,conduit,ss,ds,m,mc);
control.replay();
manager.recoverReliableEndpoint(endpoint,conduit);
control.verify();
Message msg=mc.getValue();
assertNotNull(msg);
assertNotNull(msg.getExchange());
assertSame(msg,msg.getExchange().getOutMessage());
}
BooleanVerifier InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testDefaultSequenceIdentifierGenerator(){
manager=new RMManager();
assertNull(manager.getIdGenerator());
SequenceIdentifierGenerator generator=manager.new DefaultSequenceIdentifierGenerator();
manager.setIdGenerator(generator);
assertSame(generator,manager.getIdGenerator());
Identifier id1=generator.generateSequenceIdentifier();
assertNotNull(id1);
assertNotNull(id1.getValue());
Identifier id2=generator.generateSequenceIdentifier();
assertTrue(id1 != id2);
assertTrue(!id1.getValue().equals(id2.getValue()));
control.replay();
}
InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testGetSource() throws NoSuchMethodException, RMException {
Method m=RMManager.class.getDeclaredMethod("getReliableEndpoint",new Class[]{Message.class});
manager=control.createMock(RMManager.class,new Method[]{m});
Message message=control.createMock(Message.class);
RMEndpoint rme=control.createMock(RMEndpoint.class);
EasyMock.expect(manager.getReliableEndpoint(message)).andReturn(rme);
Source source=control.createMock(Source.class);
EasyMock.expect(rme.getSource()).andReturn(source);
control.replay();
assertSame(source,manager.getSource(message));
control.verify();
control.reset();
EasyMock.expect(manager.getReliableEndpoint(message)).andReturn(null);
control.replay();
assertNull(manager.getSource(message));
control.verify();
}
InternalCallVerifier IdentityVerifier
@Test public void testGetReliableEndpointClientSideCreate() throws NoSuchMethodException, RMException {
Method m1=RMManager.class.getDeclaredMethod("createReliableEndpoint",new Class[]{Endpoint.class});
manager=control.createMock(RMManager.class,new Method[]{m1});
manager.setReliableEndpointsMap(new HashMap());
Message message=control.createMock(Message.class);
Exchange exchange=control.createMock(Exchange.class);
EasyMock.expect(message.getExchange()).andReturn(exchange).anyTimes();
Endpoint endpoint=control.createMock(Endpoint.class);
EasyMock.expect(exchange.getEndpoint()).andReturn(endpoint);
EndpointInfo ei=control.createMock(EndpointInfo.class);
EasyMock.expect(endpoint.getEndpointInfo()).andReturn(ei);
QName name=new QName("http://x.y.z/a","GreeterPort");
EasyMock.expect(ei.getName()).andReturn(name);
RMEndpoint rme=control.createMock(RMEndpoint.class);
EasyMock.expect(manager.createReliableEndpoint(endpoint)).andReturn(rme);
EasyMock.expect(exchange.getDestination()).andReturn(null);
Conduit conduit=control.createMock(Conduit.class);
EasyMock.expect(exchange.getConduit(message)).andReturn(conduit);
rme.initialise(manager.getConfiguration(),conduit,null,null,message);
EasyMock.expectLastCall();
control.replay();
assertSame(rme,manager.getReliableEndpoint(message));
control.verify();
control.reset();
EasyMock.expect(message.getExchange()).andReturn(exchange);
EasyMock.expect(exchange.getEndpoint()).andReturn(endpoint);
EasyMock.expect(endpoint.getEndpointInfo()).andReturn(ei);
EasyMock.expect(ei.getName()).andReturn(name);
control.replay();
assertSame(rme,manager.getReliableEndpoint(message));
control.verify();
}
InternalCallVerifier IdentityVerifier
@Test public void testGetNewSequence() throws NoSuchMethodException, SequenceFault, RMException {
Method m=RMManager.class.getDeclaredMethod("getSource",new Class[]{Message.class});
manager=control.createMock(RMManager.class,new Method[]{m});
Message message=control.createMock(Message.class);
Exchange exchange=control.createMock(Exchange.class);
EasyMock.expect(message.getContextualPropertyKeys()).andReturn(new HashSet()).anyTimes();
EasyMock.expect(message.getExchange()).andReturn(exchange).anyTimes();
EasyMock.expect(exchange.getOutMessage()).andReturn(message).anyTimes();
EasyMock.expect(exchange.getInMessage()).andReturn(null).anyTimes();
EasyMock.expect(exchange.getOutFaultMessage()).andReturn(null).anyTimes();
Conduit conduit=control.createMock(Conduit.class);
EasyMock.expect(exchange.getConduit(message)).andReturn(conduit).anyTimes();
Identifier inSid=control.createMock(Identifier.class);
AddressingProperties maps=control.createMock(AddressingProperties.class);
Source source=control.createMock(Source.class);
EasyMock.expect(manager.getSource(message)).andReturn(source);
EasyMock.expect(source.getCurrent(inSid)).andReturn(null);
AttributedURIType uri=control.createMock(AttributedURIType.class);
EasyMock.expect(maps.getTo()).andReturn(uri);
EasyMock.expect(uri.getValue()).andReturn("http://localhost:9001/TestPort");
EndpointReferenceType epr=RMUtils.createNoneReference();
EasyMock.expect(maps.getReplyTo()).andReturn(epr);
RMEndpoint rme=control.createMock(RMEndpoint.class);
EasyMock.expect(source.getReliableEndpoint()).andReturn(rme).times(2);
Proxy proxy=control.createMock(Proxy.class);
EasyMock.expect(rme.getProxy()).andReturn(proxy);
CreateSequenceResponseType createResponse=control.createMock(CreateSequenceResponseType.class);
proxy.createSequence(EasyMock.isA(EndpointReferenceType.class),(RelatesToType)EasyMock.isNull(),EasyMock.eq(false),EasyMock.isA(ProtocolVariation.class),EasyMock.isA(Exchange.class),CastUtils.cast(EasyMock.isA(HashMap.class),String.class,Object.class));
EasyMock.expectLastCall().andReturn(createResponse);
Servant servant=control.createMock(Servant.class);
EasyMock.expect(rme.getServant()).andReturn(servant);
servant.createSequenceResponse(createResponse,ProtocolVariation.RM10WSA200408);
EasyMock.expectLastCall();
SourceSequence sseq=control.createMock(SourceSequence.class);
EasyMock.expect(source.awaitCurrent(inSid)).andReturn(sseq);
sseq.setTarget(EasyMock.isA(EndpointReferenceType.class));
EasyMock.expectLastCall();
control.replay();
assertSame(sseq,manager.getSequence(inSid,message,maps));
control.verify();
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCustom(){
Bus bus=new SpringBusFactory().createBus("org/apache/cxf/ws/rm/custom-rmmanager.xml",false);
manager=bus.getExtension(RMManager.class);
assertNotNull("sourcePolicy is not set.",manager.getSourcePolicy());
assertNotNull("destinationPolicy is not set.",manager.getDestinationPolicy());
manager.initialise();
RMConfiguration cfg=manager.getConfiguration();
assertNotNull("RMConfiguration is not set.",cfg);
assertNotNull("deliveryAssurance is not set.",cfg.getDeliveryAssurance());
assertFalse(cfg.isExponentialBackoff());
assertEquals(10000L,cfg.getBaseRetransmissionInterval().longValue());
assertEquals(10000L,cfg.getAcknowledgementIntervalTime());
assertNull(cfg.getInactivityTimeout());
SourcePolicyType sp=manager.getSourcePolicy();
assertEquals(0L,sp.getSequenceExpiration().getTimeInMillis(new Date()));
assertEquals(0L,sp.getOfferedSequenceExpiration().getTimeInMillis(new Date()));
assertNull(sp.getAcksTo());
assertTrue(sp.isIncludeOffer());
SequenceTerminationPolicyType stp=sp.getSequenceTerminationPolicy();
assertEquals(0,stp.getMaxRanges());
assertEquals(0,stp.getMaxUnacknowledged());
assertFalse(stp.isTerminateOnShutdown());
assertEquals(0,stp.getMaxLength());
DestinationPolicyType dp=manager.getDestinationPolicy();
assertNotNull(dp.getAcksPolicy());
assertEquals(dp.getAcksPolicy().getIntraMessageThreshold(),0);
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testInitialisation(){
manager=new RMManager();
assertNull("sourcePolicy is set.",manager.getSourcePolicy());
assertNull("destinationPolicy is set.",manager.getDestinationPolicy());
manager.initialise();
RMConfiguration cfg=manager.getConfiguration();
assertNotNull("RMConfiguration is not set.",cfg);
assertNotNull("sourcePolicy is not set.",manager.getSourcePolicy());
assertNotNull("destinationPolicy is not set.",manager.getDestinationPolicy());
assertNotNull("deliveryAssirance is not set.",cfg.getDeliveryAssurance());
assertTrue(cfg.isExponentialBackoff());
assertEquals(3000L,cfg.getBaseRetransmissionInterval().longValue());
assertNull(cfg.getAcknowledgementInterval());
assertNull(cfg.getInactivityTimeout());
SourcePolicyType sp=manager.getSourcePolicy();
assertEquals(0L,sp.getSequenceExpiration().getTimeInMillis(new Date()));
assertEquals(0L,sp.getOfferedSequenceExpiration().getTimeInMillis(new Date()));
assertNull(sp.getAcksTo());
assertTrue(sp.isIncludeOffer());
SequenceTerminationPolicyType stp=sp.getSequenceTerminationPolicy();
assertEquals(0,stp.getMaxRanges());
assertEquals(0,stp.getMaxUnacknowledged());
assertTrue(stp.isTerminateOnShutdown());
assertEquals(0,stp.getMaxLength());
DestinationPolicyType dp=manager.getDestinationPolicy();
assertNotNull(dp.getAcksPolicy());
assertEquals(dp.getAcksPolicy().getIntraMessageThreshold(),10);
}
InternalCallVerifier NullVerifier
@Test public void testGetBindingFaultFactory(){
SoapBinding binding=control.createMock(SoapBinding.class);
assertNotNull(new RMManager().getBindingFaultFactory(binding));
}
InternalCallVerifier NullVerifier
@Test public void testShutdownReliableEndpoint(){
manager=new RMManager();
Endpoint e=control.createMock(Endpoint.class);
RMEndpoint rme=control.createMock(RMEndpoint.class);
control.replay();
manager.shutdownReliableEndpoint(e);
control.verify();
control.reset();
manager.getReliableEndpointsMap().put(e,rme);
rme.shutdown();
EasyMock.expectLastCall();
control.replay();
manager.shutdownReliableEndpoint(e);
assertNull(manager.getReliableEndpointsMap().get(e));
control.verify();
}
Class: org.apache.cxf.ws.rm.RMOutInterceptorTest BooleanVerifier InternalCallVerifier
@Test public void testIsRuntimeFault(){
Message message=control.createMock(Message.class);
Exchange exchange=control.createMock(Exchange.class);
EasyMock.expect(message.getExchange()).andReturn(exchange).anyTimes();
EasyMock.expect(exchange.getOutFaultMessage()).andReturn(message).anyTimes();
EasyMock.expect(message.get(FaultMode.class)).andReturn(FaultMode.RUNTIME_FAULT).anyTimes();
control.replay();
RMOutInterceptor rmi=new RMOutInterceptor();
assertTrue(rmi.isRuntimeFault(message));
control.verify();
control.reset();
EasyMock.expect(message.getExchange()).andReturn(exchange).anyTimes();
EasyMock.expect(exchange.getOutFaultMessage()).andReturn(null).anyTimes();
control.replay();
assertTrue(!rmi.isRuntimeFault(message));
control.verify();
}
Class: org.apache.cxf.ws.rm.RMUtilsTest InternalCallVerifier EqualityVerifier
@Test public void testGetName(){
Endpoint e=control.createMock(Endpoint.class);
EndpointInfo ei=control.createMock(EndpointInfo.class);
EasyMock.expect(e.getEndpointInfo()).andReturn(ei).times(2);
QName eqn=new QName("ns2","endpoint");
EasyMock.expect(ei.getName()).andReturn(eqn);
ServiceInfo si=control.createMock(ServiceInfo.class);
EasyMock.expect(ei.getService()).andReturn(si);
QName sqn=new QName("ns1","service");
EasyMock.expect(si.getName()).andReturn(sqn);
control.replay();
assertEquals("{ns1}service.{ns2}endpoint@" + Bus.DEFAULT_BUS_ID,RMUtils.getEndpointIdentifier(e));
control.reset();
EasyMock.expect(e.getEndpointInfo()).andReturn(ei).times(2);
EasyMock.expect(ei.getName()).andReturn(eqn);
EasyMock.expect(ei.getService()).andReturn(si);
EasyMock.expect(si.getName()).andReturn(sqn);
Bus b=control.createMock(Bus.class);
EasyMock.expect(b.getId()).andReturn("mybus");
control.replay();
assertEquals("{ns1}service.{ns2}endpoint@mybus",RMUtils.getEndpointIdentifier(e,b));
control.reset();
EasyMock.expect(e.getEndpointInfo()).andReturn(ei).times(2);
EasyMock.expect(ei.getName()).andReturn(eqn);
EasyMock.expect(ei.getService()).andReturn(si);
EasyMock.expect(si.getName()).andReturn(sqn);
control.replay();
Bus bus=BusFactory.getDefaultBus();
assertEquals("{ns1}service.{ns2}endpoint@" + Bus.DEFAULT_BUS_ID,RMUtils.getEndpointIdentifier(e,bus));
bus.shutdown(true);
control.reset();
EasyMock.expect(e.getEndpointInfo()).andReturn(ei).times(2);
EasyMock.expect(ei.getName()).andReturn(eqn);
EasyMock.expect(ei.getService()).andReturn(si);
EasyMock.expect(si.getName()).andReturn(sqn);
EasyMock.expect(b.getId()).andReturn("mybus-" + Bus.DEFAULT_BUS_ID + "12345");
control.replay();
assertEquals("{ns1}service.{ns2}endpoint@mybus-" + Bus.DEFAULT_BUS_ID,RMUtils.getEndpointIdentifier(e,b));
control.reset();
EasyMock.expect(e.getEndpointInfo()).andReturn(ei).times(2);
EasyMock.expect(ei.getName()).andReturn(eqn);
EasyMock.expect(ei.getService()).andReturn(si);
EasyMock.expect(si.getName()).andReturn(sqn);
EasyMock.expect(b.getId()).andReturn("mybus." + Bus.DEFAULT_BUS_ID + ".foo");
control.replay();
assertEquals("{ns1}service.{ns2}endpoint@mybus." + Bus.DEFAULT_BUS_ID + ".foo",RMUtils.getEndpointIdentifier(e,b));
}
Class: org.apache.cxf.ws.rm.ServantTest BooleanVerifier InternalCallVerifier
@Test public void testInvokeForCloseSequence(){
RMEndpoint rme=control.createMock(RMEndpoint.class);
RMManager manager=new RMManager();
Destination destination=new Destination(rme);
Source source=new Source(rme);
DestinationSequence seq=control.createMock(DestinationSequence.class);
org.apache.cxf.ws.rm.v200702.Identifier sid=new org.apache.cxf.ws.rm.v200702.Identifier();
sid.setValue("123");
EasyMock.expect(seq.getIdentifier()).andReturn(sid).anyTimes();
EasyMock.expect(rme.getDestination()).andReturn(destination).anyTimes();
EasyMock.expect(rme.getManager()).andReturn(manager).anyTimes();
EasyMock.expect(rme.getSource()).andReturn(source).anyTimes();
Message message=createTestCloseSequenceMessage(sid.getValue());
BindingOperationInfo boi=control.createMock(BindingOperationInfo.class);
OperationInfo oi=control.createMock(OperationInfo.class);
EasyMock.expect(boi.getOperationInfo()).andReturn(oi).anyTimes();
EasyMock.expect(oi.getName()).andReturn(RM11Constants.INSTANCE.getCloseSequenceOperationName()).anyTimes();
message.getExchange().put(BindingOperationInfo.class,boi);
control.replay();
TestServant servant=new TestServant(rme);
servant.invoke(message.getExchange(),message.getContent(List.class).get(0));
assertTrue(servant.called);
}
Class: org.apache.cxf.ws.rm.SourceSequenceTest BooleanVerifier InternalCallVerifier
@Test public void testCheckOfferingSequenceClosed(){
SourceSequence seq=null;
setUpSource();
RMEndpoint rme=control.createMock(RMEndpoint.class);
EasyMock.expect(source.getReliableEndpoint()).andReturn(rme).anyTimes();
Destination destination=control.createMock(Destination.class);
EasyMock.expect(rme.getDestination()).andReturn(destination).anyTimes();
DestinationSequence dseq=control.createMock(DestinationSequence.class);
Identifier did=control.createMock(Identifier.class);
EasyMock.expect(destination.getSequence(did)).andReturn(dseq).anyTimes();
EasyMock.expect(dseq.getLastMessageNumber()).andReturn(new Long(1)).anyTimes();
EasyMock.expect(did.getValue()).andReturn("dseq").anyTimes();
control.replay();
seq=new SourceSequence(id,null,did,ProtocolVariation.RM10WSA200408);
seq.setSource(source);
seq.nextMessageNumber(did,1,false);
assertTrue(seq.isLastMessage());
control.verify();
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testEqualsAndHashCode(){
SourceSequence seq=new SourceSequence(id,ProtocolVariation.RM10WSA200408);
SourceSequence otherSeq=null;
assertTrue(!seq.equals(otherSeq));
otherSeq=new SourceSequence(id,ProtocolVariation.RM10WSA200408);
assertEquals(seq,otherSeq);
assertEquals(seq.hashCode(),otherSeq.hashCode());
Identifier otherId=factory.createIdentifier();
otherId.setValue("otherSeq");
otherSeq=new SourceSequence(otherId,ProtocolVariation.RM10WSA200408);
assertTrue(!seq.equals(otherSeq));
assertTrue(seq.hashCode() != otherSeq.hashCode());
assertTrue(!seq.equals(this));
}
BooleanVerifier InternalCallVerifier
@Test public void testAllAcknowledged() throws RMException {
SourceSequence seq=new SourceSequence(id,null,null,4,false,ProtocolVariation.RM10WSA200408);
setUpSource();
seq.setSource(source);
assertTrue(!seq.allAcknowledged());
seq.setLastMessage(true);
assertTrue(!seq.allAcknowledged());
SequenceAcknowledgement ack=factory.createSequenceAcknowledgement();
SequenceAcknowledgement.AcknowledgementRange r=factory.createSequenceAcknowledgementAcknowledgementRange();
r.setLower(new Long(1));
r.setUpper(new Long(2));
ack.getAcknowledgementRange().add(r);
rq.purgeAcknowledged(seq);
EasyMock.expectLastCall();
control.replay();
seq.setAcknowledged(ack);
assertTrue(!seq.allAcknowledged());
r.setUpper(new Long(4));
assertTrue(seq.allAcknowledged());
control.verify();
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testNextMessageNumber() throws RMException {
SourceSequence seq=null;
setUpSource();
rq.purgeAcknowledged(EasyMock.isA(SourceSequence.class));
EasyMock.expectLastCall().anyTimes();
control.replay();
seq=new SourceSequence(id,ProtocolVariation.RM10WSA200408);
seq.setSource(source);
assertTrue(!nextMessages(seq,10));
control.verify();
seq=new SourceSequence(id,ProtocolVariation.RM10WSA200408);
seq.setSource(source);
stp.setMaxLength(1);
assertTrue(nextMessages(seq,10));
assertEquals(1,seq.getCurrentMessageNr());
control.verify();
seq=new SourceSequence(id,ProtocolVariation.RM10WSA200408);
seq.setSource(source);
stp.setMaxLength(5);
assertTrue(!nextMessages(seq,2));
control.verify();
seq=new SourceSequence(id,ProtocolVariation.RM10WSA200408);
seq.setSource(source);
stp.setMaxLength(0);
stp.setMaxRanges(3);
acknowledge(seq,1,2,4,5,6,8,9,10);
assertTrue(nextMessages(seq,10));
assertEquals(1,seq.getCurrentMessageNr());
control.verify();
seq=new SourceSequence(id,ProtocolVariation.RM10WSA200408);
seq.setSource(source);
stp.setMaxLength(0);
stp.setMaxRanges(4);
acknowledge(seq,1,2,4,5,6,8,9,10);
assertTrue(!nextMessages(seq,10));
control.verify();
}
BooleanVerifier InternalCallVerifier
@Test public void testSetExpires(){
SourceSequence seq=new SourceSequence(id,ProtocolVariation.RM10WSA200408);
Expires expires=factory.createExpires();
seq.setExpires(expires);
assertTrue(!seq.isExpired());
Duration d=DatatypeFactory.PT0S;
expires.setValue(d);
seq.setExpires(expires);
try {
Thread.sleep(1000);
}
catch ( InterruptedException ex) {
assertTrue(!seq.isExpired());
}
d=DatatypeFactory.createDuration("PT1S");
expires.setValue(d);
seq.setExpires(expires);
assertTrue(!seq.isExpired());
d=DatatypeFactory.createDuration("-PT1S");
expires.setValue(d);
seq.setExpires(expires);
assertTrue(seq.isExpired());
}
BooleanVerifier InternalCallVerifier IdentityVerifier EqualityVerifier HybridVerifier
@Test public void testSetAcknowledged() throws RMException {
SourceSequence seq=new SourceSequence(id,ProtocolVariation.RM10WSA200408);
setUpSource();
seq.setSource(source);
SequenceAcknowledgement ack=seq.getAcknowledgement();
ack=factory.createSequenceAcknowledgement();
SequenceAcknowledgement.AcknowledgementRange r=factory.createSequenceAcknowledgementAcknowledgementRange();
r.setLower(new Long(1));
r.setUpper(new Long(2));
ack.getAcknowledgementRange().add(r);
r=factory.createSequenceAcknowledgementAcknowledgementRange();
r.setLower(new Long(4));
r.setUpper(new Long(6));
ack.getAcknowledgementRange().add(r);
r=factory.createSequenceAcknowledgementAcknowledgementRange();
r.setLower(new Long(8));
r.setUpper(new Long(10));
ack.getAcknowledgementRange().add(r);
rq.purgeAcknowledged(seq);
EasyMock.expectLastCall();
control.replay();
seq.setAcknowledged(ack);
assertSame(ack,seq.getAcknowledgement());
assertEquals(3,ack.getAcknowledgementRange().size());
assertTrue(!seq.isAcknowledged(3));
assertTrue(seq.isAcknowledged(5));
control.verify();
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testConstructors(){
Identifier otherId=factory.createIdentifier();
otherId.setValue("otherSeq");
SourceSequence seq=null;
seq=new SourceSequence(id,ProtocolVariation.RM10WSA200408);
assertEquals(id,seq.getIdentifier());
assertTrue(!seq.isLastMessage());
assertTrue(!seq.isExpired());
assertEquals(0,seq.getCurrentMessageNr());
assertNotNull(seq.getAcknowledgement());
assertEquals(0,seq.getAcknowledgement().getAcknowledgementRange().size());
assertTrue(!seq.allAcknowledged());
assertFalse(seq.offeredBy(otherId));
Date expiry=new Date(System.currentTimeMillis() + 3600 * 1000);
seq=new SourceSequence(id,expiry,null,ProtocolVariation.RM10WSA200408);
assertEquals(id,seq.getIdentifier());
assertTrue(!seq.isLastMessage());
assertTrue(!seq.isExpired());
assertEquals(0,seq.getCurrentMessageNr());
assertNotNull(seq.getAcknowledgement());
assertEquals(0,seq.getAcknowledgement().getAcknowledgementRange().size());
assertTrue(!seq.allAcknowledged());
assertFalse(seq.offeredBy(otherId));
seq=new SourceSequence(id,expiry,otherId,ProtocolVariation.RM10WSA200408);
assertTrue(seq.offeredBy(otherId));
assertFalse(seq.offeredBy(id));
}
InternalCallVerifier EqualityVerifier
@Test public void testGetEndpointIdentfier(){
setUpSource();
String name="abc";
EasyMock.expect(source.getName()).andReturn(name);
control.replay();
SourceSequence seq=new SourceSequence(id,ProtocolVariation.RM10WSA200408);
seq.setSource(source);
assertEquals("Unexpected endpoint identifier",name,seq.getEndpointIdentifier());
control.verify();
}
Class: org.apache.cxf.ws.rm.blueprint.RMBPHandlerTest InternalCallVerifier NullVerifier
@Test public void testGetSchemaLocation(){
RMBPHandler handler=new RMBPHandler();
assertNotNull(handler.getSchemaLocation("http://cxf.apache.org/ws/rm/manager"));
assertNotNull(handler.getSchemaLocation("http://schemas.xmlsoap.org/ws/2005/02/rm/policy"));
assertNotNull(handler.getSchemaLocation("http://docs.oasis-open.org/ws-rx/wsrmp/200702"));
}
Class: org.apache.cxf.ws.rm.persistence.PersistenceUtilsTest InternalCallVerifier EqualityVerifier
@Test public void testSerialiseDeserialiseAcknowledgement(){
SequenceAcknowledgement ack=new SequenceAcknowledgement();
AcknowledgementRange range=new AcknowledgementRange();
range.setLower(new Long(1));
range.setUpper(new Long(10));
ack.getAcknowledgementRange().add(range);
PersistenceUtils utils=PersistenceUtils.getInstance();
InputStream is=utils.serialiseAcknowledgment(ack);
SequenceAcknowledgement refAck=utils.deserialiseAcknowledgment(is);
assertEquals(refAck.getAcknowledgementRange().size(),refAck.getAcknowledgementRange().size());
AcknowledgementRange refRange=refAck.getAcknowledgementRange().get(0);
assertEquals(range.getLower(),refRange.getLower());
assertEquals(range.getUpper(),refRange.getUpper());
}
Class: org.apache.cxf.ws.rm.persistence.RMMessageTest InternalCallVerifier EqualityVerifier
@Test public void testContentInputStream() throws Exception {
RMMessage msg=new RMMessage();
msg.setContent(new ByteArrayInputStream(DATA));
byte[] msgbytes=IOUtils.readBytesFromStream(msg.getContent());
assertArrayEquals(DATA,msgbytes);
}
InternalCallVerifier EqualityVerifier
@Test public void testContentCachedOutputStream() throws Exception {
RMMessage msg=new RMMessage();
CachedOutputStream co=new CachedOutputStream();
co.write(DATA);
msg.setContent(co.getInputStream());
byte[] msgbytes=IOUtils.readBytesFromStream(msg.getContent());
assertArrayEquals(DATA,msgbytes);
co.close();
}
InternalCallVerifier EqualityVerifier
@Test public void testAttributes() throws Exception {
RMMessage msg=new RMMessage();
msg.setTo(TO);
msg.setMessageNumber(1);
assertEquals(msg.getTo(),TO);
assertEquals(msg.getMessageNumber(),1);
}
Class: org.apache.cxf.ws.rm.persistence.jdbc.RMTxStoreConfigurationTest InternalCallVerifier NullVerifier
@Test public void testTxStoreWithDataSource(){
SpringBusFactory factory=new SpringBusFactory();
Bus bus=factory.createBus("org/apache/cxf/ws/rm/persistence/jdbc/txstore-ds-bean.xml");
RMManager manager=bus.getExtension(RMManager.class);
assertNotNull(manager);
RMTxStore store=(RMTxStore)manager.getStore();
assertNotNull(store.getDataSource());
assertNull(store.getConnection());
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testSetCustomTableExistsState2(){
SpringBusFactory factory=new SpringBusFactory();
Bus bus=factory.createBus("org/apache/cxf/ws/rm/persistence/jdbc/txstore-custom-error-bean2.xml");
RMManager manager=bus.getExtension(RMManager.class);
assertNotNull(manager);
RMTxStore store=(RMTxStore)manager.getStore();
assertTrue(store.isTableExistsError(new SQLException("Table exists","I6000",288)));
assertFalse(store.isTableExistsError(new SQLException("Unknown error","00000",-1)));
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testSetCustomTableExistsState(){
SpringBusFactory factory=new SpringBusFactory();
Bus bus=factory.createBus("org/apache/cxf/ws/rm/persistence/jdbc/txstore-custom-error-bean.xml");
RMManager manager=bus.getExtension(RMManager.class);
assertNotNull(manager);
RMTxStore store=(RMTxStore)manager.getStore();
assertTrue(store.isTableExistsError(new SQLException("Table exists","I6000",288)));
assertFalse(store.isTableExistsError(new SQLException("Unknown error","00000",-1)));
}
InternalCallVerifier NullVerifier
@Test public void testTxStoreWithDataSource2(){
SpringBusFactory factory=new SpringBusFactory();
Bus bus=factory.createBus("org/apache/cxf/ws/rm/persistence/jdbc/txstore-ds-bean2.xml");
RMManager manager=bus.getExtension(RMManager.class);
assertNotNull(manager);
RMTxStore store=(RMTxStore)manager.getStore();
assertNotNull(store.getDataSource());
assertNull(store.getConnection());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testTxStoreBean(){
SpringBusFactory factory=new SpringBusFactory();
Bus bus=factory.createBus("org/apache/cxf/ws/rm/persistence/jdbc/txstore-bean.xml");
RMManager manager=bus.getExtension(RMManager.class);
assertNotNull(manager);
RMTxStore store=(RMTxStore)manager.getStore();
assertNotNull(store);
assertNull("Connection should be null",store.getConnection());
assertEquals("org.apache.derby.jdbc.NoDriver",store.getDriverClassName());
assertEquals("scott",store.getUserName());
assertEquals("tiger",store.getPassword());
assertEquals("jdbc:derby://localhost:1527/rmdb;create=true",store.getUrl());
assertNull("schema should be unset",store.getSchemaName());
}
Class: org.apache.cxf.ws.rm.persistence.jdbc.RMTxStoreTest UtilityVerifier BooleanVerifier InternalCallVerifier HybridVerifier
@Test public void testReconnect() throws Exception {
long ird=store.getInitialReconnectDelay();
store.setInitialReconnectDelay(100);
SourceSequence seq=control.createMock(SourceSequence.class);
Identifier sid1=RMUtils.getWSRMFactory().createIdentifier();
sid1.setValue("sequence1");
EasyMock.expect(seq.getIdentifier()).andReturn(sid1);
EasyMock.expect(seq.getExpires()).andReturn(null);
EasyMock.expect(seq.getOfferingSequenceIdentifier()).andReturn(null);
EasyMock.expect(seq.getEndpointIdentifier()).andReturn(CLIENT_ENDPOINT_ID);
EasyMock.expect(seq.getProtocol()).andReturn(ProtocolVariation.RM10WSA200408);
try {
store.getConnection().close();
}
catch ( SQLException ex) {
}
control.replay();
try {
store.createSourceSequence(seq);
fail("Expected RMStoreException was not thrown.");
}
catch ( RMStoreException ex) {
SQLException se=(SQLException)ex.getCause();
assertTrue(se.getSQLState().startsWith("08"));
}
Thread.sleep(200);
control.reset();
EasyMock.expect(seq.getIdentifier()).andReturn(sid1);
EasyMock.expect(seq.getExpires()).andReturn(null);
EasyMock.expect(seq.getOfferingSequenceIdentifier()).andReturn(null);
EasyMock.expect(seq.getEndpointIdentifier()).andReturn(CLIENT_ENDPOINT_ID);
EasyMock.expect(seq.getProtocol()).andReturn(ProtocolVariation.RM10WSA200408);
control.replay();
store.createSourceSequence(seq);
control.verify();
store.setInitialReconnectDelay(ird);
store.removeSourceSequence(sid1);
}
Class: org.apache.cxf.ws.rm.persistence.jdbc.RMTxStoreTestBase APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testCreateSequenceStoreInboundMessage() throws SQLException, IOException {
Identifier sid1=null;
try {
DestinationSequence seq=control.createMock(DestinationSequence.class);
sid1=new Identifier();
sid1.setValue("sequence1");
EndpointReferenceType epr=RMUtils.createAnonymousReference();
EasyMock.expect(seq.getIdentifier()).andReturn(sid1);
EasyMock.expect(seq.getAcksTo()).andReturn(epr);
EasyMock.expect(seq.getEndpointIdentifier()).andReturn(SERVER_ENDPOINT_ID);
EasyMock.expect(seq.getProtocol()).andReturn(ProtocolVariation.RM10WSA200408);
control.replay();
store.createDestinationSequence(seq);
Collection seqs=store.getDestinationSequences(SERVER_ENDPOINT_ID);
assertEquals(1,seqs.size());
DestinationSequence rseq=seqs.iterator().next();
assertFalse(rseq.isAcknowledged(1));
Collection in=store.getMessages(sid1,false);
assertEquals(0,in.size());
control.reset();
EasyMock.expect(seq.getIdentifier()).andReturn(sid1).anyTimes();
EasyMock.expect(seq.getAcknowledgment()).andReturn(ack1);
EasyMock.expect(seq.getAcksTo()).andReturn(epr);
setupInboundMessage(seq,1L,null);
in=store.getMessages(sid1,false);
assertEquals(1,in.size());
checkRecoveredMessages(in);
seqs=store.getDestinationSequences(SERVER_ENDPOINT_ID);
assertEquals(1,seqs.size());
rseq=seqs.iterator().next();
assertTrue(rseq.isAcknowledged(1));
assertFalse(rseq.isAcknowledged(10));
EasyMock.expect(seq.getIdentifier()).andReturn(sid1).anyTimes();
EasyMock.expect(seq.getAcknowledgment()).andReturn(ack2);
EasyMock.expect(seq.getAcksTo()).andReturn(epr);
control.replay();
store.persistIncoming(seq,null);
control.reset();
seqs=store.getDestinationSequences(SERVER_ENDPOINT_ID);
assertEquals(1,seqs.size());
rseq=seqs.iterator().next();
assertTrue(rseq.isAcknowledged(10));
}
finally {
if (null != sid1) {
store.removeDestinationSequence(sid1);
}
Collection msgNrs=new ArrayList();
msgNrs.add(ONE);
store.removeMessages(sid1,msgNrs,false);
}
}
InternalCallVerifier NullVerifier
@Test public void testGetDestinationSequence() throws SQLException, IOException {
Identifier sid1=null;
Identifier sid2=null;
DestinationSequence seq=store.getDestinationSequence(new Identifier());
assertNull(seq);
try {
sid1=setupDestinationSequence("sequence1");
seq=store.getDestinationSequence(sid1);
assertNotNull(seq);
verifyDestinationSequence("sequence1",seq);
sid2=setupDestinationSequence("sequence2");
seq=store.getDestinationSequence(sid2);
assertNotNull(seq);
verifyDestinationSequence("sequence2",seq);
}
finally {
if (null != sid1) {
store.removeDestinationSequence(sid1);
}
if (null != sid2) {
store.removeDestinationSequence(sid2);
}
}
}
UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testCreateDeleteDestSequences(){
DestinationSequence seq=control.createMock(DestinationSequence.class);
Identifier sid1=new Identifier();
sid1.setValue("sequence1");
EndpointReferenceType epr=RMUtils.createAnonymousReference();
EasyMock.expect(seq.getIdentifier()).andReturn(sid1);
EasyMock.expect(seq.getAcksTo()).andReturn(epr);
EasyMock.expect(seq.getEndpointIdentifier()).andReturn(SERVER_ENDPOINT_ID);
EasyMock.expect(seq.getProtocol()).andReturn(ProtocolVariation.RM10WSA200408);
control.replay();
store.createDestinationSequence(seq);
control.verify();
control.reset();
EasyMock.expect(seq.getIdentifier()).andReturn(sid1);
EasyMock.expect(seq.getAcksTo()).andReturn(epr);
EasyMock.expect(seq.getEndpointIdentifier()).andReturn(SERVER_ENDPOINT_ID);
EasyMock.expect(seq.getProtocol()).andReturn(ProtocolVariation.RM10WSA200408);
control.replay();
try {
store.createDestinationSequence(seq);
fail("Expected RMStoreException was not thrown.");
}
catch ( RMStoreException ex) {
SQLException se=(SQLException)ex.getCause();
assertEquals("23505",se.getSQLState());
}
control.verify();
control.reset();
Identifier sid2=new Identifier();
sid2.setValue("sequence2");
EasyMock.expect(seq.getIdentifier()).andReturn(sid2);
epr=RMUtils.createReference(NON_ANON_ACKS_TO);
EasyMock.expect(seq.getAcksTo()).andReturn(epr);
EasyMock.expect(seq.getEndpointIdentifier()).andReturn(CLIENT_ENDPOINT_ID);
EasyMock.expect(seq.getProtocol()).andReturn(ProtocolVariation.RM10WSA200408);
control.replay();
store.createDestinationSequence(seq);
control.verify();
store.removeDestinationSequence(sid1);
store.removeDestinationSequence(sid2);
store.removeDestinationSequence(sid2);
}
UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testCreateDeleteSrcSequences(){
SourceSequence seq=control.createMock(SourceSequence.class);
Identifier sid1=new Identifier();
sid1.setValue("sequence1");
EasyMock.expect(seq.getIdentifier()).andReturn(sid1);
EasyMock.expect(seq.getExpires()).andReturn(null);
EasyMock.expect(seq.getOfferingSequenceIdentifier()).andReturn(null);
EasyMock.expect(seq.getEndpointIdentifier()).andReturn(CLIENT_ENDPOINT_ID);
EasyMock.expect(seq.getProtocol()).andReturn(ProtocolVariation.RM10WSA200408);
control.replay();
store.createSourceSequence(seq);
control.verify();
control.reset();
EasyMock.expect(seq.getIdentifier()).andReturn(sid1);
EasyMock.expect(seq.getExpires()).andReturn(null);
EasyMock.expect(seq.getOfferingSequenceIdentifier()).andReturn(null);
EasyMock.expect(seq.getEndpointIdentifier()).andReturn(CLIENT_ENDPOINT_ID);
EasyMock.expect(seq.getProtocol()).andReturn(ProtocolVariation.RM10WSA200408);
control.replay();
try {
store.createSourceSequence(seq);
fail("Expected RMStoreException was not thrown.");
}
catch ( RMStoreException ex) {
SQLException se=(SQLException)ex.getCause();
assertEquals("23505",se.getSQLState());
}
control.verify();
control.reset();
Identifier sid2=new Identifier();
sid2.setValue("sequence2");
EasyMock.expect(seq.getIdentifier()).andReturn(sid2);
EasyMock.expect(seq.getExpires()).andReturn(new Date());
Identifier sid3=new Identifier();
sid3.setValue("offeringSequence3");
EasyMock.expect(seq.getOfferingSequenceIdentifier()).andReturn(sid3);
EasyMock.expect(seq.getEndpointIdentifier()).andReturn(SERVER_ENDPOINT_ID);
EasyMock.expect(seq.getProtocol()).andReturn(ProtocolVariation.RM10WSA200408);
control.replay();
store.createSourceSequence(seq);
control.verify();
store.removeSourceSequence(sid1);
store.removeSourceSequence(sid2);
store.removeSourceSequence(sid2);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testCreateSequenceStoreOutboundMessage() throws SQLException, IOException {
Identifier sid1=null;
try {
SourceSequence seq=control.createMock(SourceSequence.class);
sid1=new Identifier();
sid1.setValue("sequence1");
EasyMock.expect(seq.getIdentifier()).andReturn(sid1);
EasyMock.expect(seq.getExpires()).andReturn(null);
EasyMock.expect(seq.getOfferingSequenceIdentifier()).andReturn(null);
EasyMock.expect(seq.getEndpointIdentifier()).andReturn(CLIENT_ENDPOINT_ID);
EasyMock.expect(seq.getProtocol()).andReturn(ProtocolVariation.RM10WSA200408);
control.replay();
store.createSourceSequence(seq);
control.reset();
Collection seqs=store.getSourceSequences(CLIENT_ENDPOINT_ID);
assertEquals(1,seqs.size());
SourceSequence rseq=seqs.iterator().next();
assertFalse(rseq.isLastMessage());
Collection out=store.getMessages(sid1,true);
assertEquals(0,out.size());
EasyMock.expect(seq.getIdentifier()).andReturn(sid1).anyTimes();
EasyMock.expect(seq.isLastMessage()).andReturn(true);
setupOutboundMessage(seq,1L,null);
out=store.getMessages(sid1,true);
assertEquals(1,out.size());
checkRecoveredMessages(out);
seqs=store.getSourceSequences(CLIENT_ENDPOINT_ID);
assertEquals(1,seqs.size());
rseq=seqs.iterator().next();
assertTrue(rseq.isLastMessage());
EasyMock.expect(seq.getIdentifier()).andReturn(sid1).anyTimes();
EasyMock.expect(seq.getCurrentMessageNr()).andReturn(2L);
EasyMock.expect(seq.isLastMessage()).andReturn(true);
control.replay();
store.persistOutgoing(seq,null);
control.reset();
seqs=store.getSourceSequences(CLIENT_ENDPOINT_ID);
assertEquals(1,seqs.size());
rseq=seqs.iterator().next();
assertEquals(2,rseq.getCurrentMessageNr());
}
finally {
if (null != sid1) {
store.removeSourceSequence(sid1);
}
Collection msgNrs=new ArrayList();
msgNrs.add(ONE);
store.removeMessages(sid1,msgNrs,true);
}
}
InternalCallVerifier NullVerifier
@Test public void testGetSourceSequence() throws SQLException, IOException {
Identifier sid1=null;
Identifier sid2=null;
SourceSequence seq=store.getSourceSequence(new Identifier());
assertNull(seq);
try {
sid1=setupSourceSequence("sequence1");
seq=store.getSourceSequence(sid1);
assertNotNull(seq);
verifySourceSequence("sequence1",seq);
sid2=setupSourceSequence("sequence2");
seq=store.getSourceSequence(sid2);
assertNotNull(seq);
verifySourceSequence("sequence2",seq);
}
finally {
if (null != sid1) {
store.removeSourceSequence(sid1);
}
if (null != sid2) {
store.removeSourceSequence(sid2);
}
}
}
InternalCallVerifier EqualityVerifier
@Test public void testGetSourceSequences() throws SQLException {
Identifier sid1=null;
Identifier sid2=null;
Collection seqs=store.getSourceSequences("unknown");
assertEquals(0,seqs.size());
try {
sid1=setupSourceSequence("sequence1");
seqs=store.getSourceSequences(CLIENT_ENDPOINT_ID);
assertEquals(1,seqs.size());
checkRecoveredSourceSequences(seqs);
sid2=setupSourceSequence("sequence2");
seqs=store.getSourceSequences(CLIENT_ENDPOINT_ID);
assertEquals(2,seqs.size());
checkRecoveredSourceSequences(seqs);
}
finally {
if (null != sid1) {
store.removeSourceSequence(sid1);
}
if (null != sid2) {
store.removeSourceSequence(sid2);
}
}
}
InternalCallVerifier EqualityVerifier
@Test public void testGetMessages() throws SQLException, IOException {
Identifier sid1=new Identifier();
sid1.setValue("sequence1");
Identifier sid2=new Identifier();
sid2.setValue("sequence2");
Collection out=store.getMessages(sid1,true);
assertEquals(0,out.size());
Collection in=store.getMessages(sid1,false);
assertEquals(0,out.size());
try {
setupMessage(sid1,ONE,null,true);
setupMessage(sid1,ONE,null,false);
out=store.getMessages(sid1,true);
assertEquals(1,out.size());
checkRecoveredMessages(out);
in=store.getMessages(sid1,false);
assertEquals(1,in.size());
checkRecoveredMessages(in);
setupMessage(sid1,TEN,NON_ANON_ACKS_TO,true);
setupMessage(sid1,TEN,NON_ANON_ACKS_TO,false);
out=store.getMessages(sid1,true);
assertEquals(2,out.size());
checkRecoveredMessages(out);
in=store.getMessages(sid1,false);
assertEquals(2,in.size());
checkRecoveredMessages(in);
}
finally {
Collection msgNrs=new ArrayList();
msgNrs.add(ONE);
msgNrs.add(TEN);
store.removeMessages(sid1,msgNrs,true);
store.removeMessages(sid1,msgNrs,false);
}
}
InternalCallVerifier EqualityVerifier
@Test public void testGetDestinationSequences() throws SQLException, IOException {
Identifier sid1=null;
Identifier sid2=null;
Collection seqs=store.getDestinationSequences("unknown");
assertEquals(0,seqs.size());
try {
sid1=setupDestinationSequence("sequence1");
seqs=store.getDestinationSequences(SERVER_ENDPOINT_ID);
assertEquals(1,seqs.size());
checkRecoveredDestinationSequences(seqs);
sid2=setupDestinationSequence("sequence2");
seqs=store.getDestinationSequences(SERVER_ENDPOINT_ID);
assertEquals(2,seqs.size());
checkRecoveredDestinationSequences(seqs);
}
finally {
if (null != sid1) {
store.removeDestinationSequence(sid1);
}
if (null != sid2) {
store.removeDestinationSequence(sid2);
}
}
}
Class: org.apache.cxf.ws.rm.persistence.jdbc.RMTxStoreTwoSchemasTest InternalCallVerifier NullVerifier
@Test public void testStoreIsolation() throws Exception {
SourceSequence seq=control.createMock(SourceSequence.class);
Identifier sid1=new Identifier();
sid1.setValue("sequence1");
EasyMock.expect(seq.getIdentifier()).andReturn(sid1);
EasyMock.expect(seq.getExpires()).andReturn(null);
EasyMock.expect(seq.getOfferingSequenceIdentifier()).andReturn(null);
EasyMock.expect(seq.getEndpointIdentifier()).andReturn(CLIENT_ENDPOINT_ID);
EasyMock.expect(seq.getProtocol()).andReturn(ProtocolVariation.RM10WSA200408);
control.replay();
store1.createSourceSequence(seq);
control.verify();
SourceSequence rseq=store1.getSourceSequence(sid1);
assertNotNull(rseq);
rseq=store2.getSourceSequence(sid1);
assertNull(rseq);
control.reset();
EasyMock.expect(seq.getIdentifier()).andReturn(sid1);
EasyMock.expect(seq.getExpires()).andReturn(null);
EasyMock.expect(seq.getOfferingSequenceIdentifier()).andReturn(null);
EasyMock.expect(seq.getEndpointIdentifier()).andReturn(CLIENT_ENDPOINT_ID);
EasyMock.expect(seq.getProtocol()).andReturn(ProtocolVariation.RM10WSA200408);
control.replay();
store2.createSourceSequence(seq);
control.verify();
rseq=store2.getSourceSequence(sid1);
assertNotNull(rseq);
RMTxStore store3=createStore(null);
store3.init();
rseq=store3.getSourceSequence(sid1);
assertNull(rseq);
store3.setSchemaName(store1.getSchemaName());
store3.init();
rseq=store3.getSourceSequence(sid1);
assertNotNull(rseq);
}
Class: org.apache.cxf.ws.rm.policy.PolicyUtilsTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testIntersect(){
RMAssertion rma=new RMAssertion();
RMConfiguration cfg0=new RMConfiguration();
assertTrue(RMPolicyUtilities.equals(cfg0,RMPolicyUtilities.intersect(rma,cfg0)));
InactivityTimeout aiat=new RMAssertion.InactivityTimeout();
aiat.setMilliseconds(new Long(7200000));
rma.setInactivityTimeout(aiat);
cfg0.setInactivityTimeout(new Long(3600000));
RMConfiguration cfg1=RMPolicyUtilities.intersect(rma,cfg0);
assertEquals(7200000L,cfg1.getInactivityTimeout().longValue());
assertNull(cfg1.getBaseRetransmissionInterval());
assertNull(cfg1.getAcknowledgementInterval());
assertFalse(cfg1.isExponentialBackoff());
BaseRetransmissionInterval abri=new RMAssertion.BaseRetransmissionInterval();
abri.setMilliseconds(new Long(20000));
rma.setBaseRetransmissionInterval(abri);
cfg0.setBaseRetransmissionInterval(new Long(10000));
cfg1=RMPolicyUtilities.intersect(rma,cfg0);
assertEquals(7200000L,cfg1.getInactivityTimeout().longValue());
assertEquals(20000L,cfg1.getBaseRetransmissionInterval().longValue());
assertNull(cfg1.getAcknowledgementInterval());
assertFalse(cfg1.isExponentialBackoff());
AcknowledgementInterval aai=new RMAssertion.AcknowledgementInterval();
aai.setMilliseconds(new Long(2000));
rma.setAcknowledgementInterval(aai);
cfg1=RMPolicyUtilities.intersect(rma,cfg0);
assertEquals(7200000L,cfg1.getInactivityTimeout().longValue());
assertEquals(20000L,cfg1.getBaseRetransmissionInterval().longValue());
assertEquals(2000L,cfg1.getAcknowledgementInterval().longValue());
assertFalse(cfg1.isExponentialBackoff());
cfg0.setExponentialBackoff(true);
cfg1=RMPolicyUtilities.intersect(rma,cfg0);
assertEquals(7200000L,cfg1.getInactivityTimeout().longValue());
assertEquals(20000L,cfg1.getBaseRetransmissionInterval().longValue());
assertEquals(2000L,cfg1.getAcknowledgementInterval().longValue());
assertTrue(cfg1.isExponentialBackoff());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier IdentityVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGetRMConfiguration(){
RMConfiguration cfg=new RMConfiguration();
cfg.setBaseRetransmissionInterval(new Long(3000));
cfg.setExponentialBackoff(true);
Message message=control.createMock(Message.class);
EasyMock.expect(message.get(AssertionInfoMap.class)).andReturn(null);
control.replay();
assertSame(cfg,RMPolicyUtilities.getRMConfiguration(cfg,message));
control.verify();
control.reset();
AssertionInfoMap aim=control.createMock(AssertionInfoMap.class);
EasyMock.expect(message.get(AssertionInfoMap.class)).andReturn(aim);
Collection ais=new ArrayList();
EasyMock.expect(aim.get(RM10Constants.RMASSERTION_QNAME)).andReturn(ais);
control.replay();
assertSame(cfg,RMPolicyUtilities.getRMConfiguration(cfg,message));
control.verify();
control.reset();
RMAssertion b=new RMAssertion();
BaseRetransmissionInterval bbri=new RMAssertion.BaseRetransmissionInterval();
bbri.setMilliseconds(new Long(2000));
b.setBaseRetransmissionInterval(bbri);
JaxbAssertion assertion=new JaxbAssertion();
assertion.setName(RM10Constants.RMASSERTION_QNAME);
assertion.setData(b);
AssertionInfo ai=new AssertionInfo(assertion);
ais.add(ai);
EasyMock.expect(message.get(AssertionInfoMap.class)).andReturn(aim);
EasyMock.expect(aim.get(RM10Constants.RMASSERTION_QNAME)).andReturn(ais);
control.replay();
RMConfiguration cfg1=RMPolicyUtilities.getRMConfiguration(cfg,message);
assertNull(cfg1.getAcknowledgementInterval());
assertNull(cfg1.getInactivityTimeout());
assertEquals(2000L,cfg1.getBaseRetransmissionInterval().longValue());
assertTrue(cfg1.isExponentialBackoff());
control.verify();
}
BooleanVerifier InternalCallVerifier
@Test public void testRMAssertionEquals(){
RMAssertion a=new RMAssertion();
assertTrue(RMPolicyUtilities.equals(a,a));
RMAssertion b=new RMAssertion();
assertTrue(RMPolicyUtilities.equals(a,b));
InactivityTimeout iat=new RMAssertion.InactivityTimeout();
iat.setMilliseconds(new Long(10));
a.setInactivityTimeout(iat);
assertTrue(!RMPolicyUtilities.equals(a,b));
b.setInactivityTimeout(iat);
assertTrue(RMPolicyUtilities.equals(a,b));
ExponentialBackoff eb=new RMAssertion.ExponentialBackoff();
a.setExponentialBackoff(eb);
assertTrue(!RMPolicyUtilities.equals(a,b));
b.setExponentialBackoff(eb);
assertTrue(RMPolicyUtilities.equals(a,b));
}
Class: org.apache.cxf.ws.rm.soap.RMSoapInInterceptorTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testDecodeAcknowledgements2() throws XMLStreamException {
SoapMessage message=setUpInboundMessage("resources/Acknowledgment2.xml");
RMSoapInInterceptor codec=new RMSoapInInterceptor();
codec.handleMessage(message);
RMProperties rmps=RMContextUtils.retrieveRMProperties(message,false);
Collection acks=rmps.getAcks();
assertNotNull(acks);
assertEquals(1,acks.size());
SequenceAcknowledgement ack=acks.iterator().next();
assertNotNull(ack);
assertEquals(1,ack.getAcknowledgementRange().size());
AcknowledgementRange r1=ack.getAcknowledgementRange().get(0);
verifyRange(r1,1,3);
assertNull(rmps.getSequence());
assertNull(rmps.getAcksRequested());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testDecodeAcknowledgements() throws XMLStreamException {
SoapMessage message=setUpInboundMessage("resources/Acknowledgment.xml");
RMSoapInInterceptor codec=new RMSoapInInterceptor();
codec.handleMessage(message);
RMProperties rmps=RMContextUtils.retrieveRMProperties(message,false);
Collection acks=rmps.getAcks();
assertNotNull(acks);
assertEquals(1,acks.size());
SequenceAcknowledgement ack=acks.iterator().next();
assertNotNull(ack);
assertEquals(ack.getIdentifier().getValue(),SEQ_IDENTIFIER);
assertEquals(2,ack.getAcknowledgementRange().size());
AcknowledgementRange r1=ack.getAcknowledgementRange().get(0);
AcknowledgementRange r2=ack.getAcknowledgementRange().get(1);
verifyRange(r1,1,1);
verifyRange(r2,3,3);
assertNull(rmps.getSequence());
assertNull(rmps.getAcksRequested());
}
BooleanVerifier InternalCallVerifier
@Test public void testGetUnderstoodHeaders() throws Exception {
RMSoapInInterceptor codec=new RMSoapInInterceptor();
Set headers=codec.getUnderstoodHeaders();
assertTrue("expected Sequence header",headers.contains(RM10Constants.SEQUENCE_QNAME));
assertTrue("expected SequenceAcknowledgment header",headers.contains(RM10Constants.SEQUENCE_ACK_QNAME));
assertTrue("expected AckRequested header",headers.contains(RM10Constants.ACK_REQUESTED_QNAME));
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testDecodeAcksRequested() throws XMLStreamException {
SoapMessage message=setUpInboundMessage("resources/Retransmission.xml");
RMSoapInInterceptor codec=new RMSoapInInterceptor();
codec.handleMessage(message);
RMProperties rmps=RMContextUtils.retrieveRMProperties(message,false);
Collection requested=rmps.getAcksRequested();
assertNotNull(requested);
assertEquals(1,requested.size());
AckRequestedType ar=requested.iterator().next();
assertNotNull(ar);
assertEquals(ar.getIdentifier().getValue(),SEQ_IDENTIFIER);
SequenceType s=rmps.getSequence();
assertNotNull(s);
assertEquals(s.getIdentifier().getValue(),SEQ_IDENTIFIER);
assertEquals(s.getMessageNumber(),MSG2_MESSAGE_NUMBER);
assertNull(rmps.getAcks());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testDecodeSequence() throws XMLStreamException {
SoapMessage message=setUpInboundMessage("resources/Message1.xml");
RMSoapInInterceptor codec=new RMSoapInInterceptor();
codec.handleMessage(message);
RMProperties rmps=RMContextUtils.retrieveRMProperties(message,false);
SequenceType st=rmps.getSequence();
assertNotNull(st);
assertEquals(st.getIdentifier().getValue(),SEQ_IDENTIFIER);
assertEquals(st.getMessageNumber(),MSG1_MESSAGE_NUMBER);
assertNull(rmps.getAcks());
assertNull(rmps.getAcksRequested());
}
Class: org.apache.cxf.ws.rm.soap.RMSoapOutInterceptorTest BooleanVerifier InternalCallVerifier
@Test public void testGetUnderstoodHeaders() throws Exception {
RMSoapOutInterceptor codec=new RMSoapOutInterceptor();
Set headers=codec.getUnderstoodHeaders();
assertTrue("expected Sequence header",headers.contains(RM10Constants.SEQUENCE_QNAME));
assertTrue("expected SequenceAcknowledgment header",headers.contains(RM10Constants.SEQUENCE_ACK_QNAME));
assertTrue("expected AckRequested header",headers.contains(RM10Constants.ACK_REQUESTED_QNAME));
}
Class: org.apache.cxf.ws.rm.soap.RetransmissionQueueImplTest APIUtilityVerifier InternalCallVerifier IdentityVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCacheUnacknowledged(){
SoapMessage message1=setUpMessage("sequence1",ONE);
SoapMessage message2=setUpMessage("sequence2",ONE);
SoapMessage message3=setUpMessage("sequence1",TWO);
setupMessagePolicies(message1);
setupMessagePolicies(message2);
setupMessagePolicies(message3);
endpoint.handleAccept("sequence1",1,message1);
EasyMock.expectLastCall();
endpoint.handleAccept("sequence2",1,message2);
EasyMock.expectLastCall();
endpoint.handleAccept("sequence1",2,message3);
EasyMock.expectLastCall();
ready(false);
assertNotNull("expected resend candidate",queue.cacheUnacknowledged(message1));
assertEquals("expected non-empty unacked map",1,queue.getUnacknowledged().size());
List sequence1List=queue.getUnacknowledged().get("sequence1");
assertNotNull("expected non-null context list",sequence1List);
assertSame("expected context list entry",message1,sequence1List.get(0).getMessage());
assertNotNull("expected resend candidate",queue.cacheUnacknowledged(message2));
assertEquals("unexpected unacked map size",2,queue.getUnacknowledged().size());
List sequence2List=queue.getUnacknowledged().get("sequence2");
assertNotNull("expected non-null context list",sequence2List);
assertSame("expected context list entry",message2,sequence2List.get(0).getMessage());
assertNotNull("expected resend candidate",queue.cacheUnacknowledged(message3));
assertEquals("un expected unacked map size",2,queue.getUnacknowledged().size());
sequence1List=queue.getUnacknowledged().get("sequence1");
assertNotNull("expected non-null context list",sequence1List);
assertSame("expected context list entry",message3,sequence1List.get(1).getMessage());
}
InternalCallVerifier EqualityVerifier
@Test public void testPurgeAcknowledgedNone(){
Long[] messageNumbers={TEN,ONE};
SourceSequence sequence=setUpSequence("sequence1",messageNumbers,new boolean[]{false,false});
List sequenceList=new ArrayList();
queue.getUnacknowledged().put("sequence1",sequenceList);
SoapMessage message1=setUpMessage("sequence1",messageNumbers[0]);
setupMessagePolicies(message1);
SoapMessage message2=setUpMessage("sequence1",messageNumbers[1]);
setupMessagePolicies(message2);
ready(false);
sequenceList.add(queue.createResendCandidate(message1));
sequenceList.add(queue.createResendCandidate(message2));
queue.purgeAcknowledged(sequence);
assertEquals("unexpected unacked map size",1,queue.getUnacknowledged().size());
assertEquals("unexpected unacked list size",2,sequenceList.size());
}
InternalCallVerifier IdentityVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCtor(){
ready(false);
assertNotNull("expected unacked map",queue.getUnacknowledged());
assertEquals("expected empty unacked map",0,queue.getUnacknowledged().size());
queue=new RetransmissionQueueImpl(null);
assertNull(queue.getManager());
queue.setManager(manager);
assertSame("Unexpected RMManager",manager,queue.getManager());
}
InternalCallVerifier EqualityVerifier
@Test public void testPurgeAcknowledgedSome(){
Long[] messageNumbers={TEN,ONE};
SourceSequence sequence=setUpSequence("sequence1",messageNumbers,new boolean[]{true,false});
List sequenceList=new ArrayList();
queue.getUnacknowledged().put("sequence1",sequenceList);
SoapMessage message1=setUpMessage("sequence1",messageNumbers[0]);
setupMessagePolicies(message1);
SoapMessage message2=setUpMessage("sequence1",messageNumbers[1]);
setupMessagePolicies(message2);
endpoint.handleAcknowledgment("sequence1",TEN,message1);
EasyMock.expectLastCall();
ready(false);
sequenceList.add(queue.createResendCandidate(message1));
sequenceList.add(queue.createResendCandidate(message2));
queue.purgeAcknowledged(sequence);
assertEquals("unexpected unacked map size",1,queue.getUnacknowledged().size());
assertEquals("unexpected unacked list size",1,sequenceList.size());
}
InternalCallVerifier EqualityVerifier
@Test public void testPurgeAcknowledgedAll(){
Long[] messageNumbers={TEN,ONE};
SourceSequence sequence=setUpSequence("sequence1",messageNumbers,new boolean[]{true,true});
List sequenceList=new ArrayList();
queue.getUnacknowledged().put("sequence1",sequenceList);
SoapMessage message1=setUpMessage("sequence1",messageNumbers[0]);
setupMessagePolicies(message1);
SoapMessage message2=setUpMessage("sequence1",messageNumbers[1]);
setupMessagePolicies(message2);
endpoint.handleAcknowledgment("sequence1",TEN,message1);
EasyMock.expectLastCall();
endpoint.handleAcknowledgment("sequence1",ONE,message2);
EasyMock.expectLastCall();
ready(false);
sequenceList.add(queue.createResendCandidate(message1));
sequenceList.add(queue.createResendCandidate(message2));
queue.purgeAcknowledged(sequence);
assertEquals("unexpected unacked map size",0,queue.getUnacknowledged().size());
assertEquals("unexpected unacked list size",0,sequenceList.size());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testCountUnacknowledged(){
Long[] messageNumbers={TEN,ONE};
SourceSequence sequence=setUpSequence("sequence1",messageNumbers,null);
List sequenceList=new ArrayList();
queue.getUnacknowledged().put("sequence1",sequenceList);
SoapMessage message1=setUpMessage("sequence1",messageNumbers[0],false);
setupMessagePolicies(message1);
SoapMessage message2=setUpMessage("sequence1",messageNumbers[1],false);
setupMessagePolicies(message2);
ready(false);
sequenceList.add(queue.createResendCandidate(message1));
sequenceList.add(queue.createResendCandidate(message2));
assertEquals("unexpected unacked count",2,queue.countUnacknowledged(sequence));
assertTrue("queue is empty",!queue.isEmpty());
}
Class: org.apache.cxf.ws.rm.soap.SoapFaultFactoryTest InternalCallVerifier EqualityVerifier
@Test public void testToString(){
SoapBinding sb=control.createMock(SoapBinding.class);
EasyMock.expect(sb.getSoapVersion()).andReturn(Soap11.getInstance());
SoapFault fault=control.createMock(SoapFault.class);
EasyMock.expect(fault.getReason()).andReturn("r");
EasyMock.expect(fault.getFaultCode()).andReturn(new QName("ns","code"));
EasyMock.expect(fault.getSubCode()).andReturn(new QName("ns","subcode"));
control.replay();
SoapFaultFactory factory=new SoapFaultFactory(sb);
assertEquals("Reason: r, code: {ns}code, subCode: {ns}subcode",factory.toString(fault));
control.verify();
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void createSoap12Fault(){
SoapBinding sb=control.createMock(SoapBinding.class);
EasyMock.expect(sb.getSoapVersion()).andReturn(Soap12.getInstance());
Identifier id=new Identifier();
id.setValue("sid");
setupSequenceFault(true,RM10Constants.UNKNOWN_SEQUENCE_FAULT_QNAME,id);
control.replay();
SoapFaultFactory factory=new SoapFaultFactory(sb);
SoapFault fault=(SoapFault)factory.createFault(sf,createInboundMessage());
assertEquals("reason",fault.getReason());
assertEquals(Soap12.getInstance().getSender(),fault.getFaultCode());
assertEquals(RM10Constants.UNKNOWN_SEQUENCE_FAULT_QNAME,fault.getSubCode());
Element elem=fault.getDetail();
assertEquals(RM10Constants.NAMESPACE_URI,elem.getNamespaceURI());
assertEquals("Identifier",elem.getLocalName());
assertNull(fault.getCause());
control.verify();
}
InternalCallVerifier IdentityVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void createSoap11Fault(){
SoapBinding sb=control.createMock(SoapBinding.class);
EasyMock.expect(sb.getSoapVersion()).andReturn(Soap11.getInstance());
setupSequenceFault(false,RM10Constants.SEQUENCE_TERMINATED_FAULT_QNAME,null);
control.replay();
SoapFaultFactory factory=new SoapFaultFactory(sb);
SoapFault fault=(SoapFault)factory.createFault(sf,createInboundMessage());
assertEquals("reason",fault.getReason());
assertEquals(Soap11.getInstance().getReceiver(),fault.getFaultCode());
assertNull(fault.getSubCode());
assertNull(fault.getDetail());
assertSame(sf,fault.getCause());
control.verify();
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void createSoap12FaultWithAcknowledgementDetail(){
SoapBinding sb=control.createMock(SoapBinding.class);
EasyMock.expect(sb.getSoapVersion()).andReturn(Soap12.getInstance());
SequenceAcknowledgement ack=new SequenceAcknowledgement();
Identifier id=new Identifier();
id.setValue("sid");
ack.setIdentifier(id);
SequenceAcknowledgement.AcknowledgementRange range=new SequenceAcknowledgement.AcknowledgementRange();
range.setLower(new Long(1));
range.setUpper(new Long(10));
ack.getAcknowledgementRange().add(range);
setupSequenceFault(true,RM10Constants.INVALID_ACKNOWLEDGMENT_FAULT_QNAME,ack);
control.replay();
SoapFaultFactory factory=new SoapFaultFactory(sb);
SoapFault fault=(SoapFault)factory.createFault(sf,createInboundMessage());
assertEquals("reason",fault.getReason());
assertEquals(Soap12.getInstance().getSender(),fault.getFaultCode());
assertEquals(RM10Constants.INVALID_ACKNOWLEDGMENT_FAULT_QNAME,fault.getSubCode());
Element elem=fault.getDetail();
assertEquals(RM10Constants.NAMESPACE_URI,elem.getNamespaceURI());
assertEquals("SequenceAcknowledgement",elem.getLocalName());
control.verify();
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void createSoap12FaultWithoutDetail(){
SoapBinding sb=control.createMock(SoapBinding.class);
EasyMock.expect(sb.getSoapVersion()).andReturn(Soap12.getInstance());
setupSequenceFault(true,RM10Constants.CREATE_SEQUENCE_REFUSED_FAULT_QNAME,null);
control.replay();
SoapFaultFactory factory=new SoapFaultFactory(sb);
SoapFault fault=(SoapFault)factory.createFault(sf,createInboundMessage());
assertEquals("reason",fault.getReason());
assertEquals(Soap12.getInstance().getSender(),fault.getFaultCode());
assertEquals(RM10Constants.CREATE_SEQUENCE_REFUSED_FAULT_QNAME,fault.getSubCode());
assertNull(fault.getDetail());
control.verify();
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void createSoap12FaultWithIdentifierDetail(){
SoapBinding sb=control.createMock(SoapBinding.class);
EasyMock.expect(sb.getSoapVersion()).andReturn(Soap12.getInstance());
Identifier id=new Identifier();
id.setValue("sid");
setupSequenceFault(true,RM10Constants.UNKNOWN_SEQUENCE_FAULT_QNAME,id);
control.replay();
SoapFaultFactory factory=new SoapFaultFactory(sb);
SoapFault fault=(SoapFault)factory.createFault(sf,createInboundMessage());
assertEquals("reason",fault.getReason());
assertEquals(Soap12.getInstance().getSender(),fault.getFaultCode());
assertEquals(RM10Constants.UNKNOWN_SEQUENCE_FAULT_QNAME,fault.getSubCode());
Element elem=fault.getDetail();
assertEquals(RM10Constants.NAMESPACE_URI,elem.getNamespaceURI());
assertEquals("Identifier",elem.getLocalName());
control.verify();
}
Class: org.apache.cxf.ws.security.cache.EHCacheUtilsTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testUseGlobalManager(){
Bus bus=BusFactory.getThreadDefaultBus();
Configuration conf=ConfigurationFactory.parseConfiguration(EHCacheManagerHolder.class.getResource("/cxf-test-ehcache.xml"));
conf.setName("myGlobalConfig");
CacheManager.newInstance(conf);
CacheManager manager=EHCacheUtils.getCacheManager(bus,EHCacheManagerHolder.class.getResource("/cxf-test-ehcache.xml"));
assertFalse(manager.getName().equals("myGlobalConfig"));
EHCacheManagerHolder.releaseCacheManger(manager);
assertEquals(Status.STATUS_SHUTDOWN,manager.getStatus());
bus.setProperty(EHCacheUtils.GLOBAL_EHCACHE_MANAGER_NAME,"myGlobalConfig");
manager=EHCacheUtils.getCacheManager(bus,EHCacheManagerHolder.class.getResource("/cxf-test-ehcache.xml"));
assertEquals("myGlobalConfig",manager.getName());
EHCacheManagerHolder.releaseCacheManger(manager);
assertEquals(Status.STATUS_ALIVE,manager.getStatus());
manager.shutdown();
assertEquals(Status.STATUS_SHUTDOWN,manager.getStatus());
bus.setProperty(EHCacheUtils.GLOBAL_EHCACHE_MANAGER_NAME,"myGlobalConfigXXX");
manager=EHCacheUtils.getCacheManager(bus,EHCacheManagerHolder.class.getResource("/cxf-test-ehcache.xml"));
assertFalse(manager.getName().equals("myGlobalConfig"));
EHCacheManagerHolder.releaseCacheManger(manager);
assertEquals(Status.STATUS_SHUTDOWN,manager.getStatus());
}
Class: org.apache.cxf.ws.security.sts.STSClientTest APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testWCFWsdl() throws Exception {
Bus bus=BusFactory.getThreadDefaultBus();
InputStream inStream=getClass().getResourceAsStream("wcf.wsdl");
Document doc=StaxUtils.read(inStream);
NodeList metadataSections=doc.getElementsByTagNameNS("http://schemas.xmlsoap.org/ws/2004/09/mex","MetadataSection");
Element wsdlDefinition=null;
List schemas=new ArrayList();
for (int i=0; i < metadataSections.getLength(); i++) {
Node node=metadataSections.item(i);
if (node instanceof Element) {
Element element=(Element)node;
String dialect=element.getAttributeNS(null,"Dialect");
if ("http://schemas.xmlsoap.org/wsdl/".equals(dialect)) {
wsdlDefinition=DOMUtils.getFirstElement(element);
}
else if ("http://www.w3.org/2001/XMLSchema".equals(dialect)) {
schemas.add(DOMUtils.getFirstElement(element));
}
}
}
assertNotNull(wsdlDefinition);
assertTrue(!schemas.isEmpty());
WSDLManager wsdlManager=bus.getExtension(WSDLManager.class);
Definition definition=wsdlManager.getDefinition(wsdlDefinition);
for ( Element schemaElement : schemas) {
QName schemaName=new QName(schemaElement.getNamespaceURI(),schemaElement.getLocalName());
ExtensibilityElement exElement=wsdlManager.getExtensionRegistry().createExtension(Types.class,schemaName);
((Schema)exElement).setElement(schemaElement);
definition.getTypes().addExtensibilityElement(exElement);
}
WSDLServiceFactory factory=new WSDLServiceFactory(bus,definition);
SourceDataBinding dataBinding=new SourceDataBinding();
factory.setDataBinding(dataBinding);
Service service=factory.create();
service.setDataBinding(dataBinding);
}
InternalCallVerifier EqualityVerifier
@Test public void testConfigureViaEPR() throws Exception {
final Set> addressingClasses=new HashSet>();
addressingClasses.add(org.apache.cxf.ws.addressing.wsdl.ObjectFactory.class);
addressingClasses.add(org.apache.cxf.ws.addressing.ObjectFactory.class);
JAXBContext ctx=JAXBContextCache.getCachedContextAndSchemas(addressingClasses,null,null,null,true).getContext();
Unmarshaller um=ctx.createUnmarshaller();
InputStream inStream=getClass().getResourceAsStream("epr.xml");
JAXBElement> el=(JAXBElement>)um.unmarshal(inStream);
EndpointReferenceType ref=(EndpointReferenceType)el.getValue();
Bus bus=BusFactory.getThreadDefaultBus();
STSClient client=new STSClient(bus);
client.configureViaEPR(ref,false);
assertEquals("http://localhost:8080/jaxws-samples-wsse-policy-trust-sts/SecurityTokenService?wsdl",client.getWsdlLocation());
assertEquals(new QName("http://docs.oasis-open.org/ws-sx/ws-trust/200512/","SecurityTokenService"),client.getServiceQName());
assertEquals(new QName("http://docs.oasis-open.org/ws-sx/ws-trust/200512/","UT_Port"),client.getEndpointQName());
}
Class: org.apache.cxf.ws.security.wss4j.CryptoCoverageCheckerTest BooleanVerifier InternalCallVerifier
@Test public void testOrder() throws Exception {
SortedSet phases=new TreeSet();
phases.add(new Phase(Phase.PRE_PROTOCOL,1));
List> lst=new ArrayList>();
lst.add(new MustUnderstandInterceptor());
lst.add(new WSS4JInInterceptor());
lst.add(new SAAJInInterceptor());
lst.add(new CryptoCoverageChecker());
PhaseInterceptorChain chain=new PhaseInterceptorChain(phases);
chain.add(lst);
String output=chain.toString();
assertTrue(output.contains("MustUnderstandInterceptor, SAAJInInterceptor, " + "WSS4JInInterceptor, CryptoCoverageChecker"));
}
Class: org.apache.cxf.ws.security.wss4j.CustomPolicyAlgorithmsTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSHA256AsymSigAlgorithm() throws Exception {
final String rsaSha2SigMethod="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
String policyName="signed_elements_policy.xml";
Policy policy=policyBuilder.getPolicy(this.getResourceAsStream(policyName));
AssertionInfoMap aim=new AssertionInfoMap(policy);
AssertionInfo assertInfo=aim.get(SP12Constants.ASYMMETRIC_BINDING).iterator().next();
AsymmetricBinding binding=(AsymmetricBinding)assertInfo.getAssertion();
binding.getAlgorithmSuite().setAsymmetricSignature(rsaSha2SigMethod);
String sigMethod=binding.getAlgorithmSuite().getAsymmetricSignature();
assertNotNull(sigMethod);
assertEquals(rsaSha2SigMethod,sigMethod);
}
Class: org.apache.cxf.ws.security.wss4j.DOMToStaxRoundTripTest UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testEncryptionAlgorithms() throws Exception {
Service service=createService();
WSSSecurityProperties inProperties=new WSSSecurityProperties();
inProperties.setCallbackHandler(new TestPwdCallback());
Properties cryptoProperties=CryptoFactory.getProperties("insecurity.properties",this.getClass().getClassLoader());
inProperties.setDecryptionCryptoProperties(cryptoProperties);
WSS4JStaxInInterceptor inhandler=new WSS4JStaxInInterceptor(inProperties);
service.getInInterceptors().add(inhandler);
Echo echo=createClientProxy();
Client client=ClientProxy.getClient(echo);
client.getInInterceptors().add(new LoggingInInterceptor());
client.getOutInterceptors().add(new LoggingOutInterceptor());
Map properties=new HashMap();
properties.put(WSHandlerConstants.ACTION,WSHandlerConstants.ENCRYPT);
properties.put(WSHandlerConstants.PW_CALLBACK_REF,new TestPwdCallback());
properties.put(WSHandlerConstants.ENC_PROP_FILE,"outsecurity.properties");
properties.put(WSHandlerConstants.USER,"myalias");
properties.put(WSHandlerConstants.ENC_KEY_TRANSPORT,WSConstants.KEYTRANSPORT_RSA15);
properties.put(WSHandlerConstants.ENC_SYM_ALGO,WSConstants.TRIPLE_DES);
WSS4JOutInterceptor ohandler=new WSS4JOutInterceptor(properties);
client.getOutInterceptors().add(ohandler);
try {
echo.echo("test");
fail("Failure expected as RSA v1.5 is not allowed by default");
}
catch ( javax.xml.ws.soap.SOAPFaultException ex) {
}
inProperties.setAllowRSA15KeyTransportAlgorithm(true);
service.getInInterceptors().remove(inhandler);
inhandler=new WSS4JStaxInInterceptor(inProperties);
service.getInInterceptors().add(inhandler);
assertEquals("test",echo.echo("test"));
}
Class: org.apache.cxf.ws.security.wss4j.SecurityActionTokenTest APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testSignature() throws Exception {
SignatureActionToken actionToken=new SignatureActionToken();
actionToken.setCryptoProperties("outsecurity.properties");
actionToken.setUser("myalias");
List actions=Collections.singletonList(new HandlerAction(WSConstants.SIGN,actionToken));
Map outProperties=new HashMap<>();
outProperties.put(WSHandlerConstants.HANDLER_ACTIONS,actions);
outProperties.put(WSHandlerConstants.PW_CALLBACK_REF,new TestPwdCallback());
Map inProperties=new HashMap<>();
inProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.SIGNATURE);
inProperties.put(WSHandlerConstants.SIG_VER_PROP_FILE,"insecurity.properties");
List xpaths=new ArrayList();
xpaths.add("//wsse:Security");
xpaths.add("//wsse:Security/ds:Signature");
List handlerResults=getResults(makeInvocation(outProperties,xpaths,inProperties));
WSSecurityEngineResult actionResult=handlerResults.get(0).getActionResults().get(WSConstants.SIGN).get(0);
X509Certificate certificate=(X509Certificate)actionResult.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
assertNotNull(certificate);
}
Class: org.apache.cxf.ws.security.wss4j.StaxCryptoCoverageCheckerTest UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testTimestamp() throws Exception {
Service service=createService();
WSSSecurityProperties inProperties=new WSSSecurityProperties();
WSS4JStaxInInterceptor inhandler=new WSS4JStaxInInterceptor(inProperties);
service.getInInterceptors().add(inhandler);
StaxCryptoCoverageChecker checker=new StaxCryptoCoverageChecker();
checker.setSignBody(false);
service.getInInterceptors().add(checker);
Echo echo=createClientProxy();
Client client=ClientProxy.getClient(echo);
client.getInInterceptors().add(new LoggingInInterceptor());
client.getOutInterceptors().add(new LoggingOutInterceptor());
WSSSecurityProperties properties=new WSSSecurityProperties();
List actions=new ArrayList();
actions.add(WSSConstants.TIMESTAMP);
properties.setActions(actions);
WSS4JStaxOutInterceptor ohandler=new WSS4JStaxOutInterceptor(properties);
client.getOutInterceptors().add(ohandler);
try {
echo.echo("test");
fail("Failure expected as Timestamp isn't signed");
}
catch ( javax.xml.ws.soap.SOAPFaultException ex) {
}
checker.setSignTimestamp(false);
assertEquals("test",echo.echo("test"));
}
UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testEncryptedBody() throws Exception {
Service service=createService();
WSSSecurityProperties inProperties=new WSSSecurityProperties();
inProperties.setCallbackHandler(new TestPwdCallback());
Properties cryptoProperties=CryptoFactory.getProperties("insecurity.properties",this.getClass().getClassLoader());
inProperties.setDecryptionCryptoProperties(cryptoProperties);
WSS4JStaxInInterceptor inhandler=new WSS4JStaxInInterceptor(inProperties);
service.getInInterceptors().add(inhandler);
StaxCryptoCoverageChecker checker=new StaxCryptoCoverageChecker();
service.getInInterceptors().add(checker);
Echo echo=createClientProxy();
Client client=ClientProxy.getClient(echo);
client.getInInterceptors().add(new LoggingInInterceptor());
client.getOutInterceptors().add(new LoggingOutInterceptor());
WSSSecurityProperties properties=new WSSSecurityProperties();
List actions=new ArrayList();
actions.add(WSSConstants.ENCRYPT);
properties.setActions(actions);
properties.setEncryptionUser("myalias");
properties.setEncryptionSymAlgorithm(WSSConstants.NS_XENC_AES128);
Properties outCryptoProperties=CryptoFactory.getProperties("outsecurity.properties",this.getClass().getClassLoader());
properties.setEncryptionCryptoProperties(outCryptoProperties);
properties.setCallbackHandler(new TestPwdCallback());
WSS4JStaxOutInterceptor ohandler=new WSS4JStaxOutInterceptor(properties);
client.getOutInterceptors().add(ohandler);
try {
echo.echo("test");
fail("Failure expected as SOAP Body isn't signed");
}
catch ( javax.xml.ws.soap.SOAPFaultException ex) {
}
checker.setSignBody(false);
assertEquals("test",echo.echo("test"));
}
UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testUsernameToken() throws Exception {
Service service=createService();
WSSSecurityProperties inProperties=new WSSSecurityProperties();
inProperties.setCallbackHandler(new TestPwdCallback());
WSS4JStaxInInterceptor inhandler=new WSS4JStaxInInterceptor(inProperties);
WSS4JPrincipalInterceptor principalInterceptor=new WSS4JPrincipalInterceptor();
principalInterceptor.setPrincipalName("username");
service.getInInterceptors().add(inhandler);
service.getInInterceptors().add(principalInterceptor);
StaxCryptoCoverageChecker checker=new StaxCryptoCoverageChecker();
checker.setSignBody(false);
checker.setEncryptUsernameToken(true);
service.getInInterceptors().add(checker);
Echo echo=createClientProxy();
Client client=ClientProxy.getClient(echo);
client.getInInterceptors().add(new LoggingInInterceptor());
client.getOutInterceptors().add(new LoggingOutInterceptor());
WSSSecurityProperties properties=new WSSSecurityProperties();
List actions=new ArrayList();
actions.add(WSSConstants.USERNAMETOKEN);
properties.setActions(actions);
properties.setUsernameTokenPasswordType(WSSConstants.UsernameTokenPasswordType.PASSWORD_TEXT);
properties.setTokenUser("username");
properties.setCallbackHandler(new TestPwdCallback());
WSS4JStaxOutInterceptor ohandler=new WSS4JStaxOutInterceptor(properties);
client.getOutInterceptors().add(ohandler);
try {
echo.echo("test");
fail("Failure expected as UsernameToken isn't encrypted");
}
catch ( javax.xml.ws.soap.SOAPFaultException ex) {
}
checker.setEncryptUsernameToken(false);
assertEquals("test",echo.echo("test"));
}
Class: org.apache.cxf.ws.security.wss4j.StaxToDOMRoundTripTest UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testEncryptionAlgorithms() throws Exception {
Service service=createService();
Map inProperties=new HashMap();
inProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.ENCRYPT);
inProperties.put(WSHandlerConstants.PW_CALLBACK_REF,new TestPwdCallback());
inProperties.put(WSHandlerConstants.DEC_PROP_FILE,"insecurity.properties");
WSS4JInInterceptor inInterceptor=new WSS4JInInterceptor(inProperties);
service.getInInterceptors().add(inInterceptor);
Echo echo=createClientProxy();
Client client=ClientProxy.getClient(echo);
client.getInInterceptors().add(new LoggingInInterceptor());
client.getOutInterceptors().add(new LoggingOutInterceptor());
WSSSecurityProperties properties=new WSSSecurityProperties();
List actions=new ArrayList();
actions.add(WSSConstants.ENCRYPT);
properties.setActions(actions);
properties.setEncryptionUser("myalias");
Properties cryptoProperties=CryptoFactory.getProperties("outsecurity.properties",this.getClass().getClassLoader());
properties.setEncryptionCryptoProperties(cryptoProperties);
properties.setCallbackHandler(new TestPwdCallback());
properties.setEncryptionKeyTransportAlgorithm("http://www.w3.org/2001/04/xmlenc#rsa-1_5");
properties.setEncryptionSymAlgorithm("http://www.w3.org/2001/04/xmlenc#tripledes-cbc");
WSS4JStaxOutInterceptor ohandler=new WSS4JStaxOutInterceptor(properties);
client.getOutInterceptors().add(ohandler);
try {
echo.echo("test");
fail("Failure expected as RSA v1.5 is not allowed by default");
}
catch ( javax.xml.ws.soap.SOAPFaultException ex) {
}
inProperties.put(WSHandlerConstants.ALLOW_RSA15_KEY_TRANSPORT_ALGORITHM,"true");
assertEquals("test",echo.echo("test"));
}
UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testEncryptionAlgorithmsConfig() throws Exception {
Service service=createService();
Map inProperties=new HashMap();
inProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.ENCRYPT);
inProperties.put(WSHandlerConstants.PW_CALLBACK_REF,new TestPwdCallback());
inProperties.put(WSHandlerConstants.DEC_PROP_FILE,"insecurity.properties");
WSS4JInInterceptor inInterceptor=new WSS4JInInterceptor(inProperties);
service.getInInterceptors().add(inInterceptor);
Echo echo=createClientProxy();
Client client=ClientProxy.getClient(echo);
client.getInInterceptors().add(new LoggingInInterceptor());
client.getOutInterceptors().add(new LoggingOutInterceptor());
Map outConfig=new HashMap();
outConfig.put(ConfigurationConstants.ACTION,ConfigurationConstants.ENCRYPT);
outConfig.put(ConfigurationConstants.ENCRYPTION_USER,"myalias");
outConfig.put(ConfigurationConstants.PW_CALLBACK_REF,new TestPwdCallback());
outConfig.put(ConfigurationConstants.ENC_KEY_TRANSPORT,"http://www.w3.org/2001/04/xmlenc#rsa-1_5");
outConfig.put(ConfigurationConstants.ENC_SYM_ALGO,"http://www.w3.org/2001/04/xmlenc#tripledes-cbc");
outConfig.put(ConfigurationConstants.ENC_SYM_ALGO,WSSConstants.NS_XENC_AES128);
outConfig.put(ConfigurationConstants.ENC_PROP_FILE,"outsecurity.properties");
WSS4JStaxOutInterceptor ohandler=new WSS4JStaxOutInterceptor(outConfig);
client.getOutInterceptors().add(ohandler);
try {
echo.echo("test");
fail("Failure expected as RSA v1.5 is not allowed by default");
}
catch ( javax.xml.ws.soap.SOAPFaultException ex) {
}
inProperties.put(WSHandlerConstants.ALLOW_RSA15_KEY_TRANSPORT_ALGORITHM,"true");
assertEquals("test",echo.echo("test"));
}
Class: org.apache.cxf.ws.security.wss4j.WSS4JFaultCodeTest UtilityVerifier BooleanVerifier InternalCallVerifier HybridVerifier
/**
* Test for WSS4JInInterceptor when it receives a message with no security header.
*/
@Test public void testNoSecurity() throws Exception {
Document doc=readDocument("wsse-request-clean.xml");
SoapMessage msg=new SoapMessage(new MessageImpl());
Exchange ex=new ExchangeImpl();
ex.setInMessage(msg);
SOAPMessage saajMsg=MessageFactory.newInstance().createMessage();
SOAPPart part=saajMsg.getSOAPPart();
part.setContent(new DOMSource(doc));
saajMsg.saveChanges();
msg.setContent(SOAPMessage.class,saajMsg);
doc=part;
byte[] docbytes=getMessageBytes(doc);
XMLStreamReader reader=StaxUtils.createXMLStreamReader(new ByteArrayInputStream(docbytes));
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
dbf.setIgnoringComments(false);
dbf.setIgnoringElementContentWhitespace(true);
dbf.setNamespaceAware(true);
DocumentBuilder db=dbf.newDocumentBuilder();
db.setEntityResolver(new NullResolver());
doc=StaxUtils.read(db,reader,false);
WSS4JInInterceptor inHandler=new WSS4JInInterceptor();
SoapMessage inmsg=new SoapMessage(new MessageImpl());
ex.setInMessage(inmsg);
inmsg.setContent(SOAPMessage.class,saajMsg);
inHandler.setProperty(WSHandlerConstants.ACTION,WSHandlerConstants.ENCRYPT);
inHandler.setProperty(WSHandlerConstants.DEC_PROP_FILE,"insecurity.properties");
inHandler.setProperty(WSHandlerConstants.PW_CALLBACK_CLASS,TestPwdCallback.class.getName());
inmsg.put(SecurityConstants.RETURN_SECURITY_ERROR,Boolean.TRUE);
try {
inHandler.handleMessage(inmsg);
fail("Expected failure on an message with no security header");
}
catch ( SoapFault fault) {
assertTrue(fault.getReason().startsWith("An error was discovered processing the header"));
QName faultCode=new QName(WSConstants.WSSE_NS,"InvalidSecurity");
assertTrue(fault.getFaultCode().equals(faultCode));
}
}
UtilityVerifier BooleanVerifier InternalCallVerifier HybridVerifier
/**
* Test that an action mismatch gets mapped to a proper fault code
*/
@Test public void testActionMismatch() throws Exception {
Document doc=readDocument("wsse-request-clean.xml");
WSS4JOutInterceptor ohandler=new WSS4JOutInterceptor();
PhaseInterceptor handler=ohandler.createEndingInterceptor();
SoapMessage msg=new SoapMessage(new MessageImpl());
Exchange ex=new ExchangeImpl();
ex.setInMessage(msg);
SOAPMessage saajMsg=MessageFactory.newInstance().createMessage();
SOAPPart part=saajMsg.getSOAPPart();
part.setContent(new DOMSource(doc));
saajMsg.saveChanges();
msg.setContent(SOAPMessage.class,saajMsg);
msg.put(WSHandlerConstants.ACTION,WSHandlerConstants.TIMESTAMP);
handler.handleMessage(msg);
doc=part;
assertValid("//wsse:Security",doc);
byte[] docbytes=getMessageBytes(doc);
XMLStreamReader reader=StaxUtils.createXMLStreamReader(new ByteArrayInputStream(docbytes));
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
dbf.setIgnoringComments(false);
dbf.setIgnoringElementContentWhitespace(true);
dbf.setNamespaceAware(true);
DocumentBuilder db=dbf.newDocumentBuilder();
db.setEntityResolver(new NullResolver());
doc=StaxUtils.read(db,reader,false);
WSS4JInInterceptor inHandler=new WSS4JInInterceptor();
SoapMessage inmsg=new SoapMessage(new MessageImpl());
ex.setInMessage(inmsg);
inmsg.setContent(SOAPMessage.class,saajMsg);
inHandler.setProperty(WSHandlerConstants.ACTION,WSHandlerConstants.TIMESTAMP + " " + WSHandlerConstants.USERNAME_TOKEN);
inHandler.setProperty(WSHandlerConstants.PW_CALLBACK_CLASS,TestPwdCallback.class.getName());
inmsg.put(SecurityConstants.RETURN_SECURITY_ERROR,Boolean.TRUE);
try {
inHandler.handleMessage(inmsg);
fail("Expected failure on an action mismatch");
}
catch ( SoapFault fault) {
assertTrue(fault.getReason().startsWith("An error was discovered processing the header"));
QName faultCode=new QName(WSConstants.WSSE_NS,"InvalidSecurity");
assertTrue(fault.getFaultCode().equals(faultCode));
}
}
UtilityVerifier BooleanVerifier InternalCallVerifier HybridVerifier
/**
* Test that an invalid Timestamp gets mapped to a proper fault code
*/
@Test public void testInvalidTimestamp() throws Exception {
Document doc=readDocument("wsse-request-clean.xml");
WSS4JOutInterceptor ohandler=new WSS4JOutInterceptor();
PhaseInterceptor handler=ohandler.createEndingInterceptor();
SoapMessage msg=new SoapMessage(new MessageImpl());
Exchange ex=new ExchangeImpl();
ex.setInMessage(msg);
SOAPMessage saajMsg=MessageFactory.newInstance().createMessage();
SOAPPart part=saajMsg.getSOAPPart();
part.setContent(new DOMSource(doc));
saajMsg.saveChanges();
msg.setContent(SOAPMessage.class,saajMsg);
msg.put(WSHandlerConstants.ACTION,WSHandlerConstants.TIMESTAMP);
msg.put(WSHandlerConstants.TTL_TIMESTAMP,"1");
handler.handleMessage(msg);
doc=part;
assertValid("//wsse:Security",doc);
byte[] docbytes=getMessageBytes(doc);
XMLStreamReader reader=StaxUtils.createXMLStreamReader(new ByteArrayInputStream(docbytes));
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
dbf.setIgnoringComments(false);
dbf.setIgnoringElementContentWhitespace(true);
dbf.setNamespaceAware(true);
DocumentBuilder db=dbf.newDocumentBuilder();
db.setEntityResolver(new NullResolver());
doc=StaxUtils.read(db,reader,false);
WSS4JInInterceptor inHandler=new WSS4JInInterceptor();
SoapMessage inmsg=new SoapMessage(new MessageImpl());
ex.setInMessage(inmsg);
inmsg.setContent(SOAPMessage.class,saajMsg);
inHandler.setProperty(WSHandlerConstants.ACTION,WSHandlerConstants.TIMESTAMP);
inHandler.setProperty(WSHandlerConstants.TTL_TIMESTAMP,"1");
inmsg.put(SecurityConstants.RETURN_SECURITY_ERROR,Boolean.TRUE);
try {
Thread.sleep(1250);
inHandler.handleMessage(inmsg);
fail("Expected failure on an invalid Timestamp");
}
catch ( SoapFault fault) {
assertTrue(fault.getReason().contains("Invalid timestamp"));
QName faultCode=new QName(WSConstants.WSSE_NS,"MessageExpired");
assertTrue(fault.getFaultCode().equals(faultCode));
}
}
Class: org.apache.cxf.ws.security.wss4j.WSS4JInOutTest APIUtilityVerifier BooleanVerifier InternalCallVerifier IdentityVerifier NullVerifier HybridVerifier
@Test public void testEncryptedUsernameToken() throws Exception {
Map outProperties=new HashMap();
outProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.USERNAME_TOKEN + " " + WSHandlerConstants.ENCRYPT);
outProperties.put(WSHandlerConstants.ENC_PROP_FILE,"outsecurity.properties");
outProperties.put(WSHandlerConstants.USER,"alice");
outProperties.put("password","alicePassword");
outProperties.put(WSHandlerConstants.ENCRYPTION_USER,"myalias");
outProperties.put(WSHandlerConstants.ENCRYPTION_PARTS,"{Content}{" + WSConstants.WSSE_NS + "}UsernameToken");
Map inProperties=new HashMap();
inProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.USERNAME_TOKEN + " " + WSHandlerConstants.ENCRYPT);
inProperties.put(WSHandlerConstants.DEC_PROP_FILE,"insecurity.properties");
inProperties.put(WSHandlerConstants.PW_CALLBACK_CLASS,"org.apache.cxf.ws.security.wss4j.TestPwdCallback");
List xpaths=new ArrayList();
xpaths.add("//wsse:Security");
SoapMessage inmsg=makeInvocation(outProperties,xpaths,inProperties);
List handlerResults=getResults(inmsg);
assertNotNull(handlerResults);
assertSame(handlerResults.size(),1);
final java.util.List protectionResults=handlerResults.get(0).getResults();
assertNotNull(protectionResults);
assertSame(protectionResults.size(),2);
final Principal p1=(Principal)protectionResults.get(0).get(WSSecurityEngineResult.TAG_PRINCIPAL);
final Principal p2=(Principal)protectionResults.get(1).get(WSSecurityEngineResult.TAG_PRINCIPAL);
assertTrue(p1 instanceof UsernameTokenPrincipal || p2 instanceof UsernameTokenPrincipal);
Principal utPrincipal=p1 instanceof UsernameTokenPrincipal ? p1 : p2;
SecurityContext securityContext=inmsg.get(SecurityContext.class);
assertNotNull(securityContext);
assertSame(securityContext.getUserPrincipal(),utPrincipal);
}
APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testSignature() throws Exception {
Map outProperties=new HashMap();
outProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.SIGNATURE);
outProperties.put(WSHandlerConstants.SIG_PROP_FILE,"outsecurity.properties");
outProperties.put(WSHandlerConstants.USER,"myalias");
outProperties.put("password","myAliasPassword");
Map inProperties=new HashMap();
inProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.SIGNATURE);
inProperties.put(WSHandlerConstants.SIG_VER_PROP_FILE,"insecurity.properties");
List xpaths=new ArrayList();
xpaths.add("//wsse:Security");
xpaths.add("//wsse:Security/ds:Signature");
List handlerResults=getResults(makeInvocation(outProperties,xpaths,inProperties));
WSSecurityEngineResult actionResult=handlerResults.get(0).getActionResults().get(WSConstants.SIGN).get(0);
X509Certificate certificate=(X509Certificate)actionResult.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
assertNotNull(certificate);
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testPKIPath() throws Exception {
Map outProperties=new HashMap();
outProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.SIGNATURE);
outProperties.put(WSHandlerConstants.USER,"alice");
outProperties.put(WSHandlerConstants.SIG_PROP_FILE,"alice.properties");
outProperties.put(WSHandlerConstants.PW_CALLBACK_CLASS,KeystorePasswordCallback.class.getName());
outProperties.put(WSHandlerConstants.SIG_KEY_ID,"DirectReference");
outProperties.put(WSHandlerConstants.USE_SINGLE_CERTIFICATE,"false");
Map inProperties=new HashMap();
inProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.SIGNATURE);
inProperties.put(WSHandlerConstants.SIG_VER_PROP_FILE,"cxfca.properties");
List xpaths=new ArrayList();
xpaths.add("//wsse:Security");
xpaths.add("//wsse:Security/ds:Signature");
List handlerResults=getResults(makeInvocation(outProperties,xpaths,inProperties));
WSSecurityEngineResult actionResult=handlerResults.get(0).getActionResults().get(WSConstants.SIGN).get(0);
X509Certificate[] certificates=(X509Certificate[])actionResult.get(WSSecurityEngineResult.TAG_X509_CERTIFICATES);
assertNotNull(certificates);
assertEquals(certificates.length,2);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testCustomProcessor() throws Exception {
Document doc=readDocument("wsse-request-clean.xml");
WSS4JOutInterceptor ohandler=new WSS4JOutInterceptor();
PhaseInterceptor handler=ohandler.createEndingInterceptor();
SoapMessage msg=new SoapMessage(new MessageImpl());
Exchange ex=new ExchangeImpl();
ex.setInMessage(msg);
SOAPMessage saajMsg=MessageFactory.newInstance().createMessage();
SOAPPart part=saajMsg.getSOAPPart();
part.setContent(new DOMSource(doc));
saajMsg.saveChanges();
msg.setContent(SOAPMessage.class,saajMsg);
msg.put(WSHandlerConstants.ACTION,WSHandlerConstants.SIGNATURE);
msg.put(WSHandlerConstants.SIG_PROP_FILE,"outsecurity.properties");
msg.put(WSHandlerConstants.USER,"myalias");
msg.put("password","myAliasPassword");
handler.handleMessage(msg);
doc=part;
assertValid("//wsse:Security",doc);
assertValid("//wsse:Security/ds:Signature",doc);
byte[] docbytes=getMessageBytes(doc);
XMLStreamReader reader=StaxUtils.createXMLStreamReader(new ByteArrayInputStream(docbytes));
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
dbf.setIgnoringComments(false);
dbf.setIgnoringElementContentWhitespace(true);
dbf.setNamespaceAware(true);
DocumentBuilder db=dbf.newDocumentBuilder();
db.setEntityResolver(new NullResolver());
doc=StaxUtils.read(db,reader,false);
final Map properties=new HashMap();
properties.put(WSS4JInInterceptor.PROCESSOR_MAP,createCustomProcessorMap());
WSS4JInInterceptor inHandler=new WSS4JInInterceptor(properties);
SoapMessage inmsg=new SoapMessage(new MessageImpl());
ex.setInMessage(inmsg);
inmsg.setContent(SOAPMessage.class,saajMsg);
inHandler.setProperty(WSHandlerConstants.ACTION,WSHandlerConstants.NO_SECURITY);
inHandler.handleMessage(inmsg);
List results=getResults(inmsg);
assertTrue(results != null && results.size() == 1);
List signatureResults=results.get(0).getActionResults().get(WSConstants.SIGN);
assertTrue(signatureResults == null || signatureResults.size() == 0);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testCustomProcessorObject() throws Exception {
Document doc=readDocument("wsse-request-clean.xml");
WSS4JOutInterceptor ohandler=new WSS4JOutInterceptor();
PhaseInterceptor handler=ohandler.createEndingInterceptor();
SoapMessage msg=new SoapMessage(new MessageImpl());
Exchange ex=new ExchangeImpl();
ex.setInMessage(msg);
SOAPMessage saajMsg=MessageFactory.newInstance().createMessage();
SOAPPart part=saajMsg.getSOAPPart();
part.setContent(new DOMSource(doc));
saajMsg.saveChanges();
msg.setContent(SOAPMessage.class,saajMsg);
msg.put(WSHandlerConstants.ACTION,WSHandlerConstants.SIGNATURE);
msg.put(WSHandlerConstants.SIG_PROP_FILE,"outsecurity.properties");
msg.put(WSHandlerConstants.USER,"myalias");
msg.put("password","myAliasPassword");
handler.handleMessage(msg);
doc=part;
assertValid("//wsse:Security",doc);
assertValid("//wsse:Security/ds:Signature",doc);
byte[] docbytes=getMessageBytes(doc);
XMLStreamReader reader=StaxUtils.createXMLStreamReader(new ByteArrayInputStream(docbytes));
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
dbf.setIgnoringComments(false);
dbf.setIgnoringElementContentWhitespace(true);
dbf.setNamespaceAware(true);
DocumentBuilder db=dbf.newDocumentBuilder();
db.setEntityResolver(new NullResolver());
doc=StaxUtils.read(db,reader,false);
final Map properties=new HashMap();
final Map customMap=new HashMap();
customMap.put(new QName(WSConstants.SIG_NS,WSConstants.SIG_LN),CustomProcessor.class);
properties.put(WSS4JInInterceptor.PROCESSOR_MAP,customMap);
WSS4JInInterceptor inHandler=new WSS4JInInterceptor(properties);
SoapMessage inmsg=new SoapMessage(new MessageImpl());
ex.setInMessage(inmsg);
inmsg.setContent(SOAPMessage.class,saajMsg);
inHandler.setProperty(WSHandlerConstants.ACTION,WSHandlerConstants.SIGNATURE);
inHandler.handleMessage(inmsg);
List results=getResults(inmsg);
assertTrue(results != null && results.size() == 1);
List signatureResults=results.get(0).getActionResults().get(WSConstants.SIGN);
assertTrue(signatureResults.size() == 1);
Object obj=signatureResults.get(0).get("foo");
assertNotNull(obj);
assertEquals(obj.getClass().getName(),CustomProcessor.class.getName());
}
BooleanVerifier InternalCallVerifier
@Test public void testOrder() throws Exception {
SortedSet phases=new TreeSet();
phases.add(new Phase(Phase.PRE_PROTOCOL,1));
List> lst=new ArrayList>();
lst.add(new MustUnderstandInterceptor());
lst.add(new WSS4JInInterceptor());
lst.add(new SAAJInInterceptor());
PhaseInterceptorChain chain=new PhaseInterceptorChain(phases);
chain.add(lst);
String output=chain.toString();
assertTrue(output.contains("MustUnderstandInterceptor, SAAJInInterceptor, WSS4JInInterceptor"));
}
APIUtilityVerifier InternalCallVerifier NullVerifier
@Test public void testDirectReferenceSignature() throws Exception {
Map outProperties=new HashMap();
outProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.SIGNATURE);
outProperties.put(WSHandlerConstants.SIG_PROP_FILE,"outsecurity.properties");
outProperties.put(WSHandlerConstants.USER,"myalias");
outProperties.put(WSHandlerConstants.SIG_KEY_ID,"DirectReference");
outProperties.put("password","myAliasPassword");
Map inProperties=new HashMap();
inProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.SIGNATURE);
inProperties.put(WSHandlerConstants.SIG_VER_PROP_FILE,"insecurity.properties");
List xpaths=new ArrayList();
xpaths.add("//wsse:Security");
xpaths.add("//wsse:Security/wsse:BinarySecurityToken");
xpaths.add("//wsse:Security/ds:Signature");
List handlerResults=getResults(makeInvocation(outProperties,xpaths,inProperties));
WSSecurityEngineResult actionResult=handlerResults.get(0).getActionResults().get(WSConstants.SIGN).get(0);
X509Certificate certificate=(X509Certificate)actionResult.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
assertNotNull(certificate);
}
Class: org.apache.cxf.ws.security.wss4j.saml.DOMToStaxSamlTest UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testSaml2TokenHOK() throws Exception {
Service service=createService();
WSSSecurityProperties inProperties=new WSSSecurityProperties();
Properties cryptoProperties=CryptoFactory.getProperties("insecurity.properties",this.getClass().getClassLoader());
inProperties.setSignatureVerificationCryptoProperties(cryptoProperties);
CustomStaxSamlValidator validator=new CustomStaxSamlValidator();
inProperties.addValidator(WSConstants.SAML_TOKEN,validator);
inProperties.addValidator(WSConstants.SAML2_TOKEN,validator);
WSS4JStaxInInterceptor inhandler=new WSS4JStaxInInterceptor(inProperties);
service.getInInterceptors().add(inhandler);
Echo echo=createClientProxy();
Client client=ClientProxy.getClient(echo);
client.getInInterceptors().add(new LoggingInInterceptor());
client.getOutInterceptors().add(new LoggingOutInterceptor());
Map properties=new HashMap();
properties.put(WSHandlerConstants.ACTION,WSHandlerConstants.SAML_TOKEN_SIGNED);
SAML2CallbackHandler callbackHandler=new SAML2CallbackHandler();
callbackHandler.setConfirmationMethod(SAML2Constants.CONF_HOLDER_KEY);
callbackHandler.setSignAssertion(true);
properties.put(WSHandlerConstants.SAML_CALLBACK_REF,callbackHandler);
properties.put(WSHandlerConstants.SIG_KEY_ID,"DirectReference");
properties.put(WSHandlerConstants.USER,"alice");
properties.put(WSHandlerConstants.PW_CALLBACK_REF,new PasswordCallbackHandler());
properties.put(WSHandlerConstants.SIG_PROP_FILE,"alice.properties");
WSS4JOutInterceptor ohandler=new WSS4JOutInterceptor(properties);
client.getOutInterceptors().add(ohandler);
try {
echo.echo("test");
fail("Failure expected on receiving sender vouches instead of HOK");
}
catch ( javax.xml.ws.soap.SOAPFaultException ex) {
}
validator.setRequireSenderVouches(false);
try {
echo.echo("test");
fail("Failure expected on receiving a SAML 1.1 Token instead of SAML 2.0");
}
catch ( javax.xml.ws.soap.SOAPFaultException ex) {
}
validator.setRequireSAML1Assertion(false);
assertEquals("test",echo.echo("test"));
}
UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testSaml1TokenHOK() throws Exception {
Service service=createService();
WSSSecurityProperties inProperties=new WSSSecurityProperties();
Properties cryptoProperties=CryptoFactory.getProperties("insecurity.properties",this.getClass().getClassLoader());
inProperties.setSignatureVerificationCryptoProperties(cryptoProperties);
CustomStaxSamlValidator validator=new CustomStaxSamlValidator();
inProperties.addValidator(WSConstants.SAML_TOKEN,validator);
inProperties.addValidator(WSConstants.SAML2_TOKEN,validator);
WSS4JStaxInInterceptor inhandler=new WSS4JStaxInInterceptor(inProperties);
service.getInInterceptors().add(inhandler);
Echo echo=createClientProxy();
Client client=ClientProxy.getClient(echo);
client.getInInterceptors().add(new LoggingInInterceptor());
client.getOutInterceptors().add(new LoggingOutInterceptor());
Map properties=new HashMap();
properties.put(WSHandlerConstants.ACTION,WSHandlerConstants.SAML_TOKEN_SIGNED);
SAML1CallbackHandler callbackHandler=new SAML1CallbackHandler();
callbackHandler.setConfirmationMethod(SAML1Constants.CONF_HOLDER_KEY);
callbackHandler.setSignAssertion(true);
properties.put(WSHandlerConstants.SAML_CALLBACK_REF,callbackHandler);
properties.put(WSHandlerConstants.SIG_KEY_ID,"DirectReference");
properties.put(WSHandlerConstants.USER,"alice");
properties.put(WSHandlerConstants.PW_CALLBACK_REF,new PasswordCallbackHandler());
properties.put(WSHandlerConstants.SIG_PROP_FILE,"alice.properties");
WSS4JOutInterceptor ohandler=new WSS4JOutInterceptor(properties);
client.getOutInterceptors().add(ohandler);
try {
echo.echo("test");
fail("Failure expected on receiving sender vouches instead of HOK");
}
catch ( javax.xml.ws.soap.SOAPFaultException ex) {
}
validator.setRequireSenderVouches(false);
assertEquals("test",echo.echo("test"));
}
Class: org.apache.cxf.ws.security.wss4j.saml.SamlTokenTest APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testSaml2TokenSignedSenderVouches() throws Exception {
Map outProperties=new HashMap();
outProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.SAML_TOKEN_SIGNED);
outProperties.put(WSHandlerConstants.SAML_CALLBACK_CLASS,"org.apache.cxf.ws.security.wss4j.saml.SAML2CallbackHandler");
outProperties.put(WSHandlerConstants.SIG_KEY_ID,"DirectReference");
outProperties.put(WSHandlerConstants.USER,"alice");
outProperties.put("password","password");
outProperties.put(WSHandlerConstants.SIG_PROP_FILE,"alice.properties");
Map inProperties=new HashMap();
inProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.SAML_TOKEN_UNSIGNED + " " + WSHandlerConstants.SIGNATURE);
inProperties.put(WSHandlerConstants.SIG_VER_PROP_FILE,"insecurity.properties");
final Map customMap=new HashMap();
CustomSamlValidator validator=new CustomSamlValidator();
validator.setRequireSAML1Assertion(false);
customMap.put(WSConstants.SAML_TOKEN,validator);
customMap.put(WSConstants.SAML2_TOKEN,validator);
inProperties.put(WSS4JInInterceptor.VALIDATOR_MAP,customMap);
List xpaths=new ArrayList();
xpaths.add("//wsse:Security");
xpaths.add("//wsse:Security/saml2:Assertion");
Map inMessageProperties=new HashMap();
inMessageProperties.put(SecurityConstants.VALIDATE_SAML_SUBJECT_CONFIRMATION,"false");
Message message=makeInvocation(outProperties,xpaths,inProperties,inMessageProperties);
final List handlerResults=CastUtils.cast((List>)message.get(WSHandlerConstants.RECV_RESULTS));
WSSecurityEngineResult actionResult=handlerResults.get(0).getActionResults().get(WSConstants.ST_UNSIGNED).get(0);
SamlAssertionWrapper receivedAssertion=(SamlAssertionWrapper)actionResult.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
assertTrue(receivedAssertion != null && receivedAssertion.getSaml2() != null);
assert !receivedAssertion.isSigned();
}
APIUtilityVerifier UtilityVerifier BooleanVerifier InternalCallVerifier HybridVerifier
/**
* This test creates a holder-of-key SAML1 Assertion, and sends it in the security header
* to the provider.
*/
@Test public void testSaml1TokenHOK() throws Exception {
Map outProperties=new HashMap();
outProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.SAML_TOKEN_SIGNED);
outProperties.put(WSHandlerConstants.SIG_KEY_ID,"DirectReference");
outProperties.put(WSHandlerConstants.USER,"alice");
outProperties.put("password","password");
outProperties.put(WSHandlerConstants.SIG_PROP_FILE,"alice.properties");
SAML1CallbackHandler callbackHandler=new SAML1CallbackHandler();
callbackHandler.setConfirmationMethod(SAML1Constants.CONF_HOLDER_KEY);
callbackHandler.setSignAssertion(true);
outProperties.put(WSHandlerConstants.SAML_CALLBACK_REF,callbackHandler);
Map inProperties=new HashMap();
inProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.SAML_TOKEN_SIGNED + " " + WSHandlerConstants.SIGNATURE);
inProperties.put(WSHandlerConstants.SIG_VER_PROP_FILE,"insecurity.properties");
final Map customMap=new HashMap();
CustomSamlValidator validator=new CustomSamlValidator();
customMap.put(WSConstants.SAML_TOKEN,validator);
customMap.put(WSConstants.SAML2_TOKEN,validator);
inProperties.put(WSS4JInInterceptor.VALIDATOR_MAP,customMap);
List xpaths=new ArrayList();
xpaths.add("//wsse:Security");
xpaths.add("//wsse:Security/saml1:Assertion");
try {
makeInvocation(outProperties,xpaths,inProperties);
fail("Failure expected in SAML Validator");
}
catch ( Fault ex) {
}
validator.setRequireSenderVouches(false);
Message message=makeInvocation(outProperties,xpaths,inProperties);
final List handlerResults=CastUtils.cast((List>)message.get(WSHandlerConstants.RECV_RESULTS));
WSSecurityEngineResult actionResult=handlerResults.get(0).getActionResults().get(WSConstants.ST_SIGNED).get(0);
SamlAssertionWrapper receivedAssertion=(SamlAssertionWrapper)actionResult.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
assertTrue(receivedAssertion != null && receivedAssertion.getSaml1() != null);
assert receivedAssertion.isSigned();
actionResult=handlerResults.get(0).getActionResults().get(WSConstants.SIGN).get(0);
assertTrue(actionResult != null);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
/**
* This test creates a SAML2 Assertion and sends it in the security header to the provider.
* An attribute is created per role. There are several attributes with the same name.
*/
@Test public void testSaml2TokenWithRolesSingleValue() throws Exception {
Map outProperties=new HashMap();
outProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.SAML_TOKEN_UNSIGNED);
outProperties.put(WSHandlerConstants.SIG_KEY_ID,"DirectReference");
outProperties.put(WSHandlerConstants.USER,"alice");
outProperties.put("password","password");
outProperties.put(WSHandlerConstants.SIG_PROP_FILE,"alice.properties");
SAML2CallbackHandler callbackHandler=new SAML2CallbackHandler(false);
callbackHandler.setConfirmationMethod(SAML2Constants.CONF_HOLDER_KEY);
callbackHandler.setSignAssertion(true);
callbackHandler.setStatement(Statement.ATTR);
callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
outProperties.put(WSHandlerConstants.SAML_CALLBACK_REF,callbackHandler);
Map inProperties=new HashMap();
inProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.SAML_TOKEN_SIGNED);
inProperties.put(WSHandlerConstants.SIG_VER_PROP_FILE,"insecurity.properties");
final Map customMap=new HashMap();
CustomSamlValidator validator=new CustomSamlValidator();
validator.setRequireSAML1Assertion(false);
validator.setRequireSenderVouches(false);
validator.setRequireBearer(true);
customMap.put(WSConstants.SAML_TOKEN,validator);
customMap.put(WSConstants.SAML2_TOKEN,validator);
inProperties.put(WSS4JInInterceptor.VALIDATOR_MAP,customMap);
List xpaths=new ArrayList();
xpaths.add("//wsse:Security");
xpaths.add("//wsse:Security/saml2:Assertion");
Map inMessageProperties=new HashMap();
inMessageProperties.put(SecurityConstants.VALIDATE_SAML_SUBJECT_CONFIRMATION,"false");
Message message=makeInvocation(outProperties,xpaths,inProperties,inMessageProperties);
final List handlerResults=CastUtils.cast((List>)message.get(WSHandlerConstants.RECV_RESULTS));
SecurityContext sc=message.get(SecurityContext.class);
assertNotNull(sc);
assertTrue(sc.isUserInRole("user"));
assertTrue(sc.isUserInRole("admin"));
WSSecurityEngineResult actionResult=handlerResults.get(0).getActionResults().get(WSConstants.ST_SIGNED).get(0);
SamlAssertionWrapper receivedAssertion=(SamlAssertionWrapper)actionResult.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
assertTrue(receivedAssertion != null && receivedAssertion.getSaml2() != null);
assertTrue(receivedAssertion.isSigned());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
@Test public void testSaml1TokenSignedSenderVouches() throws Exception {
Map outProperties=new HashMap();
outProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.SAML_TOKEN_SIGNED);
outProperties.put(WSHandlerConstants.SAML_CALLBACK_CLASS,"org.apache.cxf.ws.security.wss4j.saml.SAML1CallbackHandler");
outProperties.put(WSHandlerConstants.SIG_KEY_ID,"DirectReference");
outProperties.put(WSHandlerConstants.USER,"alice");
outProperties.put("password","password");
outProperties.put(WSHandlerConstants.SIG_PROP_FILE,"alice.properties");
Map inProperties=new HashMap();
inProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.SAML_TOKEN_UNSIGNED + " " + WSHandlerConstants.SIGNATURE);
inProperties.put(WSHandlerConstants.SIG_VER_PROP_FILE,"insecurity.properties");
final Map customMap=new HashMap();
CustomSamlValidator validator=new CustomSamlValidator();
customMap.put(WSConstants.SAML_TOKEN,validator);
customMap.put(WSConstants.SAML2_TOKEN,validator);
inProperties.put(WSS4JInInterceptor.VALIDATOR_MAP,customMap);
List xpaths=new ArrayList();
xpaths.add("//wsse:Security");
xpaths.add("//wsse:Security/saml1:Assertion");
Map inMessageProperties=new HashMap();
Message message=makeInvocation(outProperties,xpaths,inProperties,inMessageProperties);
final List handlerResults=CastUtils.cast((List>)message.get(WSHandlerConstants.RECV_RESULTS));
WSSecurityEngineResult actionResult=handlerResults.get(0).getActionResults().get(WSConstants.ST_UNSIGNED).get(0);
SamlAssertionWrapper receivedAssertion=(SamlAssertionWrapper)actionResult.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
assertTrue(receivedAssertion != null && receivedAssertion.getSaml1() != null);
assert !receivedAssertion.isSigned();
}
APIUtilityVerifier UtilityVerifier BooleanVerifier InternalCallVerifier HybridVerifier
/**
* This test creates a holder-of-key SAML2 Assertion, and sends it in the security header
* to the provider.
*/
@Test public void testSaml2TokenHOK() throws Exception {
Map outProperties=new HashMap();
outProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.SAML_TOKEN_SIGNED);
outProperties.put(WSHandlerConstants.SIG_KEY_ID,"DirectReference");
outProperties.put(WSHandlerConstants.USER,"alice");
outProperties.put("password","password");
outProperties.put(WSHandlerConstants.SIG_PROP_FILE,"alice.properties");
SAML2CallbackHandler callbackHandler=new SAML2CallbackHandler();
callbackHandler.setConfirmationMethod(SAML2Constants.CONF_HOLDER_KEY);
callbackHandler.setSignAssertion(true);
outProperties.put(WSHandlerConstants.SAML_CALLBACK_REF,callbackHandler);
Map inProperties=new HashMap();
inProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.SAML_TOKEN_SIGNED + " " + WSHandlerConstants.SIGNATURE);
inProperties.put(WSHandlerConstants.SIG_VER_PROP_FILE,"insecurity.properties");
final Map customMap=new HashMap();
CustomSamlValidator validator=new CustomSamlValidator();
customMap.put(WSConstants.SAML_TOKEN,validator);
customMap.put(WSConstants.SAML2_TOKEN,validator);
inProperties.put(WSS4JInInterceptor.VALIDATOR_MAP,customMap);
List xpaths=new ArrayList();
xpaths.add("//wsse:Security");
xpaths.add("//wsse:Security/saml2:Assertion");
try {
makeInvocation(outProperties,xpaths,inProperties);
fail("Failure expected in SAML Validator");
}
catch ( Fault ex) {
}
validator.setRequireSenderVouches(false);
try {
makeInvocation(outProperties,xpaths,inProperties);
fail("Failure expected in SAML Validator");
}
catch ( Fault ex) {
}
validator.setRequireSAML1Assertion(false);
Message message=makeInvocation(outProperties,xpaths,inProperties);
final List handlerResults=CastUtils.cast((List>)message.get(WSHandlerConstants.RECV_RESULTS));
WSSecurityEngineResult actionResult=handlerResults.get(0).getActionResults().get(WSConstants.ST_SIGNED).get(0);
SamlAssertionWrapper receivedAssertion=(SamlAssertionWrapper)actionResult.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
assertTrue(receivedAssertion != null && receivedAssertion.getSaml2() != null);
assert receivedAssertion.isSigned();
actionResult=handlerResults.get(0).getActionResults().get(WSConstants.SIGN).get(0);
assertTrue(actionResult != null);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
/**
* This test creates a SAML2 Assertion and sends it in the security header to the provider.
* An single attribute is created for the roles but multiple attribute value elements.
*/
@Test public void testSaml2TokenWithRoles() throws Exception {
Map outProperties=new HashMap();
outProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.SAML_TOKEN_UNSIGNED);
outProperties.put(WSHandlerConstants.SIG_KEY_ID,"DirectReference");
outProperties.put(WSHandlerConstants.USER,"alice");
outProperties.put("password","password");
outProperties.put(WSHandlerConstants.SIG_PROP_FILE,"alice.properties");
SAML2CallbackHandler callbackHandler=new SAML2CallbackHandler();
callbackHandler.setConfirmationMethod(SAML2Constants.CONF_HOLDER_KEY);
callbackHandler.setSignAssertion(true);
callbackHandler.setStatement(Statement.ATTR);
callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
outProperties.put(WSHandlerConstants.SAML_CALLBACK_REF,callbackHandler);
Map inProperties=new HashMap();
inProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.SAML_TOKEN_SIGNED);
inProperties.put(WSHandlerConstants.SIG_VER_PROP_FILE,"insecurity.properties");
final Map customMap=new HashMap();
CustomSamlValidator validator=new CustomSamlValidator();
validator.setRequireSAML1Assertion(false);
validator.setRequireSenderVouches(false);
validator.setRequireBearer(true);
customMap.put(WSConstants.SAML_TOKEN,validator);
customMap.put(WSConstants.SAML2_TOKEN,validator);
inProperties.put(WSS4JInInterceptor.VALIDATOR_MAP,customMap);
List xpaths=new ArrayList();
xpaths.add("//wsse:Security");
xpaths.add("//wsse:Security/saml2:Assertion");
Map inMessageProperties=new HashMap();
inMessageProperties.put(SecurityConstants.VALIDATE_SAML_SUBJECT_CONFIRMATION,"false");
Message message=makeInvocation(outProperties,xpaths,inProperties,inMessageProperties);
final List handlerResults=CastUtils.cast((List>)message.get(WSHandlerConstants.RECV_RESULTS));
SecurityContext sc=message.get(SecurityContext.class);
assertNotNull(sc);
assertTrue(sc.isUserInRole("user"));
assertTrue(sc.isUserInRole("admin"));
WSSecurityEngineResult actionResult=handlerResults.get(0).getActionResults().get(WSConstants.ST_SIGNED).get(0);
SamlAssertionWrapper receivedAssertion=(SamlAssertionWrapper)actionResult.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
assertTrue(receivedAssertion != null && receivedAssertion.getSaml2() != null);
assertTrue(receivedAssertion.isSigned());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier
/**
* This test creates a SAML2 Assertion and sends it in the security header to the provider.
*/
@Test public void testSaml2Token() throws Exception {
Map outProperties=new HashMap();
outProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.SAML_TOKEN_UNSIGNED);
outProperties.put(WSHandlerConstants.SAML_CALLBACK_CLASS,"org.apache.cxf.ws.security.wss4j.saml.SAML2CallbackHandler");
Map inProperties=new HashMap();
inProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.SAML_TOKEN_UNSIGNED);
final Map customMap=new HashMap();
CustomSamlValidator validator=new CustomSamlValidator();
validator.setRequireSAML1Assertion(false);
customMap.put(WSConstants.SAML_TOKEN,validator);
customMap.put(WSConstants.SAML2_TOKEN,validator);
inProperties.put(WSS4JInInterceptor.VALIDATOR_MAP,customMap);
List xpaths=new ArrayList();
xpaths.add("//wsse:Security");
xpaths.add("//wsse:Security/saml2:Assertion");
Map inMessageProperties=new HashMap();
inMessageProperties.put(SecurityConstants.VALIDATE_SAML_SUBJECT_CONFIRMATION,"false");
Message message=makeInvocation(outProperties,xpaths,inProperties,inMessageProperties);
final List handlerResults=CastUtils.cast((List>)message.get(WSHandlerConstants.RECV_RESULTS));
WSSecurityEngineResult actionResult=handlerResults.get(0).getActionResults().get(WSConstants.ST_UNSIGNED).get(0);
SamlAssertionWrapper receivedAssertion=(SamlAssertionWrapper)actionResult.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
assertTrue(receivedAssertion != null && receivedAssertion.getSaml2() != null);
assert !receivedAssertion.isSigned();
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
/**
* This test creates a SAML1 Assertion and sends it in the security header to the provider.
*/
@Test public void testSaml1TokenWithRoles() throws Exception {
Map outProperties=new HashMap();
outProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.SAML_TOKEN_UNSIGNED);
outProperties.put(WSHandlerConstants.SIG_KEY_ID,"DirectReference");
outProperties.put(WSHandlerConstants.USER,"alice");
outProperties.put("password","password");
outProperties.put(WSHandlerConstants.SIG_PROP_FILE,"alice.properties");
SAML1CallbackHandler callbackHandler=new SAML1CallbackHandler();
callbackHandler.setConfirmationMethod(SAML1Constants.CONF_HOLDER_KEY);
callbackHandler.setSignAssertion(true);
callbackHandler.setStatement(Statement.ATTR);
callbackHandler.setConfirmationMethod(SAML1Constants.CONF_BEARER);
outProperties.put(WSHandlerConstants.SAML_CALLBACK_REF,callbackHandler);
Map inProperties=new HashMap();
inProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.SAML_TOKEN_SIGNED);
inProperties.put(WSHandlerConstants.SIG_VER_PROP_FILE,"insecurity.properties");
final Map customMap=new HashMap();
CustomSamlValidator validator=new CustomSamlValidator();
validator.setRequireSAML1Assertion(true);
validator.setRequireSenderVouches(false);
validator.setRequireBearer(true);
customMap.put(WSConstants.SAML_TOKEN,validator);
customMap.put(WSConstants.SAML2_TOKEN,validator);
inProperties.put(WSS4JInInterceptor.VALIDATOR_MAP,customMap);
List xpaths=new ArrayList();
xpaths.add("//wsse:Security");
xpaths.add("//wsse:Security/saml1:Assertion");
Map inMessageProperties=new HashMap();
inMessageProperties.put(SecurityConstants.VALIDATE_SAML_SUBJECT_CONFIRMATION,"false");
Message message=makeInvocation(outProperties,xpaths,inProperties,inMessageProperties);
final List handlerResults=CastUtils.cast((List>)message.get(WSHandlerConstants.RECV_RESULTS));
SecurityContext sc=message.get(SecurityContext.class);
assertNotNull(sc);
assertTrue(sc.isUserInRole("user"));
assertTrue(sc.isUserInRole("admin"));
WSSecurityEngineResult actionResult=handlerResults.get(0).getActionResults().get(WSConstants.ST_SIGNED).get(0);
SamlAssertionWrapper receivedAssertion=(SamlAssertionWrapper)actionResult.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
assertTrue(receivedAssertion != null && receivedAssertion.getSaml1() != null);
assertTrue(receivedAssertion.isSigned());
}
Class: org.apache.cxf.ws.security.wss4j.saml.StaxToDOMSamlTest UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testSaml2TokenHOKConfig() throws Exception {
Service service=createService();
Map inProperties=new HashMap();
inProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.SAML_TOKEN_SIGNED + " " + WSHandlerConstants.SIGNATURE);
inProperties.put(WSHandlerConstants.SIG_VER_PROP_FILE,"insecurity.properties");
final Map customMap=new HashMap();
CustomSamlValidator validator=new CustomSamlValidator();
customMap.put(WSConstants.SAML_TOKEN,validator);
customMap.put(WSConstants.SAML2_TOKEN,validator);
inProperties.put(WSS4JInInterceptor.VALIDATOR_MAP,customMap);
WSS4JInInterceptor inInterceptor=new WSS4JInInterceptor(inProperties);
service.getInInterceptors().add(inInterceptor);
Echo echo=createClientProxy();
Client client=ClientProxy.getClient(echo);
client.getInInterceptors().add(new LoggingInInterceptor());
client.getOutInterceptors().add(new LoggingOutInterceptor());
Map outConfig=new HashMap();
outConfig.put(ConfigurationConstants.ACTION,ConfigurationConstants.SAML_TOKEN_SIGNED);
SAML2CallbackHandler callbackHandler=new SAML2CallbackHandler();
callbackHandler.setSignAssertion(true);
callbackHandler.setConfirmationMethod(SAML2Constants.CONF_HOLDER_KEY);
outConfig.put(ConfigurationConstants.SAML_CALLBACK_REF,callbackHandler);
outConfig.put(ConfigurationConstants.PW_CALLBACK_REF,new PasswordCallbackHandler());
outConfig.put(ConfigurationConstants.SIGNATURE_USER,"alice");
outConfig.put(ConfigurationConstants.SIG_PROP_FILE,"alice.properties");
outConfig.put(ConfigurationConstants.SIG_KEY_ID,"DirectReference");
outConfig.put(ConfigurationConstants.PW_CALLBACK_REF,new PasswordCallbackHandler());
WSS4JStaxOutInterceptor ohandler=new WSS4JStaxOutInterceptor(outConfig);
client.getOutInterceptors().add(ohandler);
try {
echo.echo("test");
fail("Failure expected on receiving sender vouches instead of HOK");
}
catch ( javax.xml.ws.soap.SOAPFaultException ex) {
}
validator.setRequireSenderVouches(false);
try {
echo.echo("test");
fail("Failure expected on receiving a SAML 1.1 Token instead of SAML 2.0");
}
catch ( javax.xml.ws.soap.SOAPFaultException ex) {
}
validator.setRequireSAML1Assertion(false);
assertEquals("test",echo.echo("test"));
}
UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testSaml1TokenHOKConfig() throws Exception {
Service service=createService();
Map inProperties=new HashMap();
inProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.SAML_TOKEN_SIGNED + " " + WSHandlerConstants.SIGNATURE);
inProperties.put(WSHandlerConstants.SIG_VER_PROP_FILE,"insecurity.properties");
final Map customMap=new HashMap();
CustomSamlValidator validator=new CustomSamlValidator();
customMap.put(WSConstants.SAML_TOKEN,validator);
customMap.put(WSConstants.SAML2_TOKEN,validator);
inProperties.put(WSS4JInInterceptor.VALIDATOR_MAP,customMap);
WSS4JInInterceptor inInterceptor=new WSS4JInInterceptor(inProperties);
service.getInInterceptors().add(inInterceptor);
Echo echo=createClientProxy();
Client client=ClientProxy.getClient(echo);
client.getInInterceptors().add(new LoggingInInterceptor());
client.getOutInterceptors().add(new LoggingOutInterceptor());
Map outConfig=new HashMap();
outConfig.put(ConfigurationConstants.ACTION,ConfigurationConstants.SAML_TOKEN_SIGNED);
SAML1CallbackHandler callbackHandler=new SAML1CallbackHandler();
callbackHandler.setSignAssertion(true);
callbackHandler.setConfirmationMethod(SAML1Constants.CONF_HOLDER_KEY);
outConfig.put(ConfigurationConstants.SAML_CALLBACK_REF,callbackHandler);
outConfig.put(ConfigurationConstants.PW_CALLBACK_REF,new PasswordCallbackHandler());
outConfig.put(ConfigurationConstants.SIGNATURE_USER,"alice");
outConfig.put(ConfigurationConstants.SIG_PROP_FILE,"alice.properties");
outConfig.put(ConfigurationConstants.SIG_KEY_ID,"DirectReference");
outConfig.put(ConfigurationConstants.PW_CALLBACK_REF,new PasswordCallbackHandler());
WSS4JStaxOutInterceptor ohandler=new WSS4JStaxOutInterceptor(outConfig);
client.getOutInterceptors().add(ohandler);
try {
echo.echo("test");
fail("Failure expected on receiving sender vouches instead of HOK");
}
catch ( javax.xml.ws.soap.SOAPFaultException ex) {
}
validator.setRequireSenderVouches(false);
assertEquals("test",echo.echo("test"));
}
UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testSaml2TokenHOK() throws Exception {
Service service=createService();
Map inProperties=new HashMap();
inProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.SAML_TOKEN_SIGNED + " " + WSHandlerConstants.SIGNATURE);
inProperties.put(WSHandlerConstants.SIG_VER_PROP_FILE,"insecurity.properties");
final Map customMap=new HashMap();
CustomSamlValidator validator=new CustomSamlValidator();
customMap.put(WSConstants.SAML_TOKEN,validator);
customMap.put(WSConstants.SAML2_TOKEN,validator);
inProperties.put(WSS4JInInterceptor.VALIDATOR_MAP,customMap);
WSS4JInInterceptor inInterceptor=new WSS4JInInterceptor(inProperties);
service.getInInterceptors().add(inInterceptor);
Echo echo=createClientProxy();
Client client=ClientProxy.getClient(echo);
client.getInInterceptors().add(new LoggingInInterceptor());
client.getOutInterceptors().add(new LoggingOutInterceptor());
WSSSecurityProperties properties=new WSSSecurityProperties();
List actions=new ArrayList();
actions.add(WSSConstants.SAML_TOKEN_SIGNED);
properties.setActions(actions);
SAML2CallbackHandler callbackHandler=new SAML2CallbackHandler();
callbackHandler.setSignAssertion(true);
callbackHandler.setConfirmationMethod(SAML2Constants.CONF_HOLDER_KEY);
properties.setSamlCallbackHandler(callbackHandler);
properties.setCallbackHandler(new PasswordCallbackHandler());
properties.setSignatureUser("alice");
Properties cryptoProperties=CryptoFactory.getProperties("alice.properties",this.getClass().getClassLoader());
properties.setSignatureCryptoProperties(cryptoProperties);
properties.setSignatureKeyIdentifier(WSSecurityTokenConstants.KEYIDENTIFIER_SECURITY_TOKEN_DIRECT_REFERENCE);
WSS4JStaxOutInterceptor ohandler=new WSS4JStaxOutInterceptor(properties);
client.getOutInterceptors().add(ohandler);
try {
echo.echo("test");
fail("Failure expected on receiving sender vouches instead of HOK");
}
catch ( javax.xml.ws.soap.SOAPFaultException ex) {
}
validator.setRequireSenderVouches(false);
try {
echo.echo("test");
fail("Failure expected on receiving a SAML 1.1 Token instead of SAML 2.0");
}
catch ( javax.xml.ws.soap.SOAPFaultException ex) {
}
validator.setRequireSAML1Assertion(false);
assertEquals("test",echo.echo("test"));
}
UtilityVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testSaml1TokenHOK() throws Exception {
Service service=createService();
Map inProperties=new HashMap();
inProperties.put(WSHandlerConstants.ACTION,WSHandlerConstants.SAML_TOKEN_SIGNED + " " + WSHandlerConstants.SIGNATURE);
inProperties.put(WSHandlerConstants.SIG_VER_PROP_FILE,"insecurity.properties");
final Map customMap=new HashMap();
CustomSamlValidator validator=new CustomSamlValidator();
customMap.put(WSConstants.SAML_TOKEN,validator);
customMap.put(WSConstants.SAML2_TOKEN,validator);
inProperties.put(WSS4JInInterceptor.VALIDATOR_MAP,customMap);
WSS4JInInterceptor inInterceptor=new WSS4JInInterceptor(inProperties);
service.getInInterceptors().add(inInterceptor);
Echo echo=createClientProxy();
Client client=ClientProxy.getClient(echo);
client.getInInterceptors().add(new LoggingInInterceptor());
client.getOutInterceptors().add(new LoggingOutInterceptor());
WSSSecurityProperties properties=new WSSSecurityProperties();
List actions=new ArrayList();
actions.add(WSSConstants.SAML_TOKEN_SIGNED);
properties.setActions(actions);
SAML1CallbackHandler callbackHandler=new SAML1CallbackHandler();
callbackHandler.setSignAssertion(true);
callbackHandler.setConfirmationMethod(SAML1Constants.CONF_HOLDER_KEY);
properties.setSamlCallbackHandler(callbackHandler);
properties.setSignatureUser("alice");
Properties cryptoProperties=CryptoFactory.getProperties("alice.properties",this.getClass().getClassLoader());
properties.setSignatureCryptoProperties(cryptoProperties);
properties.setSignatureKeyIdentifier(WSSecurityTokenConstants.KEYIDENTIFIER_SECURITY_TOKEN_DIRECT_REFERENCE);
properties.setCallbackHandler(new PasswordCallbackHandler());
WSS4JStaxOutInterceptor ohandler=new WSS4JStaxOutInterceptor(properties);
client.getOutInterceptors().add(ohandler);
try {
echo.echo("test");
fail("Failure expected on receiving sender vouches instead of HOK");
}
catch ( javax.xml.ws.soap.SOAPFaultException ex) {
}
validator.setRequireSenderVouches(false);
assertEquals("test",echo.echo("test"));
}
Class: org.apache.cxf.wsdl.interceptors.DocLiteralInInterceptorTest InternalCallVerifier EqualityVerifier
@Test public void testUnmarshalSourceData() throws Exception {
XMLStreamReader reader=StaxUtils.createXMLStreamReader(getClass().getResourceAsStream("resources/multiPartDocLitBareReq.xml"));
assertEquals(XMLStreamConstants.START_ELEMENT,reader.nextTag());
XMLStreamReader filteredReader=new PartialXMLStreamReader(reader,new QName("http://schemas.xmlsoap.org/soap/envelope/","Body"));
StaxUtils.read(filteredReader);
assertEquals(XMLStreamConstants.START_ELEMENT,reader.nextTag());
Message m=new MessageImpl();
Exchange exchange=new ExchangeImpl();
Service service=control.createMock(Service.class);
exchange.put(Service.class,service);
EasyMock.expect(service.getDataBinding()).andReturn(new SourceDataBinding());
EasyMock.expect(service.size()).andReturn(0).anyTimes();
EasyMock.expect(service.isEmpty()).andReturn(true).anyTimes();
Endpoint endpoint=control.createMock(Endpoint.class);
exchange.put(Endpoint.class,endpoint);
OperationInfo operationInfo=new OperationInfo();
operationInfo.setProperty("operation.is.synthetic",Boolean.TRUE);
MessageInfo messageInfo=new MessageInfo(operationInfo,Type.INPUT,new QName("http://foo.com","bar"));
messageInfo.addMessagePart(new MessagePartInfo(new QName("http://foo.com","partInfo1"),null));
messageInfo.addMessagePart(new MessagePartInfo(new QName("http://foo.com","partInfo2"),null));
messageInfo.addMessagePart(new MessagePartInfo(new QName("http://foo.com","partInfo3"),null));
messageInfo.addMessagePart(new MessagePartInfo(new QName("http://foo.com","partInfo4"),null));
for ( MessagePartInfo mpi : messageInfo.getMessageParts()) {
mpi.setMessageContainer(messageInfo);
}
operationInfo.setInput("inputName",messageInfo);
BindingOperationInfo boi=new BindingOperationInfo(null,operationInfo);
exchange.put(BindingOperationInfo.class,boi);
EndpointInfo endpointInfo=control.createMock(EndpointInfo.class);
BindingInfo binding=control.createMock(BindingInfo.class);
EasyMock.expect(endpoint.getEndpointInfo()).andReturn(endpointInfo).anyTimes();
EasyMock.expect(endpointInfo.getBinding()).andReturn(binding).anyTimes();
EasyMock.expect(binding.getProperties()).andReturn(new HashMap()).anyTimes();
EasyMock.expect(endpointInfo.getProperties()).andReturn(new HashMap()).anyTimes();
EasyMock.expect(endpoint.size()).andReturn(0).anyTimes();
EasyMock.expect(endpoint.isEmpty()).andReturn(true).anyTimes();
ServiceInfo serviceInfo=control.createMock(ServiceInfo.class);
EasyMock.expect(endpointInfo.getService()).andReturn(serviceInfo).anyTimes();
EasyMock.expect(serviceInfo.getName()).andReturn(new QName("http://foo.com","service")).anyTimes();
InterfaceInfo interfaceInfo=control.createMock(InterfaceInfo.class);
EasyMock.expect(serviceInfo.getInterface()).andReturn(interfaceInfo).anyTimes();
EasyMock.expect(interfaceInfo.getName()).andReturn(new QName("http://foo.com","interface")).anyTimes();
EasyMock.expect(endpointInfo.getName()).andReturn(new QName("http://foo.com","endpoint")).anyTimes();
EasyMock.expect(endpointInfo.getProperty("URI",URI.class)).andReturn(new URI("dummy")).anyTimes();
List operations=new ArrayList();
EasyMock.expect(interfaceInfo.getOperations()).andReturn(operations).anyTimes();
m.setExchange(exchange);
m.put(Message.SCHEMA_VALIDATION_ENABLED,false);
m.setContent(XMLStreamReader.class,reader);
control.replay();
new DocLiteralInInterceptor().handleMessage(m);
MessageContentsList params=(MessageContentsList)m.getContent(List.class);
assertEquals(4,params.size());
assertEquals("StringDefaultInputElem",((DOMSource)params.get(0)).getNode().getFirstChild().getNodeName());
assertEquals("IntParamInElem",((DOMSource)params.get(1)).getNode().getFirstChild().getNodeName());
}
InternalCallVerifier EqualityVerifier
@Test public void testUnmarshalSourceDataWrapped() throws Exception {
XMLStreamReader reader=StaxUtils.createXMLStreamReader(getClass().getResourceAsStream("resources/docLitWrappedReq.xml"));
assertEquals(XMLStreamConstants.START_ELEMENT,reader.nextTag());
XMLStreamReader filteredReader=new PartialXMLStreamReader(reader,new QName("http://schemas.xmlsoap.org/soap/envelope/","Body"));
StaxUtils.read(filteredReader);
assertEquals(XMLStreamConstants.START_ELEMENT,reader.nextTag());
Message m=new MessageImpl();
m.put(DocLiteralInInterceptor.KEEP_PARAMETERS_WRAPPER,true);
Exchange exchange=new ExchangeImpl();
Service service=control.createMock(Service.class);
exchange.put(Service.class,service);
EasyMock.expect(service.getDataBinding()).andReturn(new SourceDataBinding()).anyTimes();
EasyMock.expect(service.size()).andReturn(0).anyTimes();
EasyMock.expect(service.isEmpty()).andReturn(true).anyTimes();
Endpoint endpoint=control.createMock(Endpoint.class);
exchange.put(Endpoint.class,endpoint);
OperationInfo operationInfo=new OperationInfo();
MessageInfo messageInfo=new MessageInfo(operationInfo,Type.INPUT,new QName(NS,"foo"));
messageInfo.addMessagePart(new MessagePartInfo(new QName(NS,"personId"),null));
messageInfo.addMessagePart(new MessagePartInfo(new QName(NS,"ssn"),null));
messageInfo.getMessagePart(0).setConcreteName(new QName(NS,"personId"));
messageInfo.getMessagePart(1).setConcreteName(new QName(NS,"ssn"));
operationInfo.setInput("inputName",messageInfo);
OperationInfo operationInfoWrapper=new OperationInfo();
MessageInfo messageInfoWrapper=new MessageInfo(operationInfo,Type.INPUT,new QName(NS,"foo"));
messageInfoWrapper.addMessagePart(new MessagePartInfo(new QName(NS,"GetPerson"),null));
messageInfoWrapper.getMessagePart(0).setConcreteName(new QName(NS,"GetPerson"));
operationInfoWrapper.setInput("inputName",messageInfoWrapper);
operationInfoWrapper.setUnwrappedOperation(operationInfo);
ServiceInfo serviceInfo=control.createMock(ServiceInfo.class);
EasyMock.expect(serviceInfo.getName()).andReturn(new QName("http://foo.com","service")).anyTimes();
InterfaceInfo interfaceInfo=control.createMock(InterfaceInfo.class);
EasyMock.expect(serviceInfo.getInterface()).andReturn(interfaceInfo).anyTimes();
EasyMock.expect(interfaceInfo.getName()).andReturn(new QName("http://foo.com","interface")).anyTimes();
BindingInfo bindingInfo=new BindingInfo(serviceInfo,"");
BindingOperationInfo boi=new BindingOperationInfo(bindingInfo,operationInfoWrapper);
exchange.put(BindingOperationInfo.class,boi);
EndpointInfo endpointInfo=control.createMock(EndpointInfo.class);
BindingInfo binding=control.createMock(BindingInfo.class);
EasyMock.expect(endpoint.getEndpointInfo()).andReturn(endpointInfo).anyTimes();
EasyMock.expect(endpointInfo.getBinding()).andReturn(binding).anyTimes();
EasyMock.expect(binding.getProperties()).andReturn(new HashMap()).anyTimes();
EasyMock.expect(endpointInfo.getProperties()).andReturn(new HashMap()).anyTimes();
EasyMock.expect(endpoint.size()).andReturn(0).anyTimes();
EasyMock.expect(endpoint.isEmpty()).andReturn(true).anyTimes();
EasyMock.expect(endpointInfo.getService()).andReturn(serviceInfo).anyTimes();
EasyMock.expect(endpointInfo.getName()).andReturn(new QName("http://foo.com","endpoint")).anyTimes();
EasyMock.expect(endpointInfo.getProperty("URI",URI.class)).andReturn(new URI("dummy")).anyTimes();
List operations=new ArrayList();
EasyMock.expect(interfaceInfo.getOperations()).andReturn(operations).anyTimes();
m.setExchange(exchange);
m.put(Message.SCHEMA_VALIDATION_ENABLED,false);
m.setContent(XMLStreamReader.class,reader);
control.replay();
new DocLiteralInInterceptor().handleMessage(m);
MessageContentsList params=(MessageContentsList)m.getContent(List.class);
assertEquals(1,params.size());
Map ns=new HashMap();
ns.put("ns",NS);
XPathUtils xu=new XPathUtils(ns);
assertEquals("hello",xu.getValueString("//ns:GetPerson/ns:personId",((DOMSource)params.get(0)).getNode().getFirstChild()));
assertEquals("1234",xu.getValueString("//ns:GetPerson/ns:ssn",((DOMSource)params.get(0)).getNode().getFirstChild()));
}
Class: org.apache.cxf.wsdl11.NSManagerTest InternalCallVerifier EqualityVerifier
@Test public void testGetPrefix(){
NSManager nsMan=new NSManager();
assertEquals("wsaw",nsMan.getPrefixFromNS(JAXWSAConstants.NS_WSAW));
assertEquals("soap",nsMan.getPrefixFromNS(WSDLConstants.NS_SOAP));
assertEquals("soap12",nsMan.getPrefixFromNS(WSDLConstants.NS_SOAP12));
}
Class: org.apache.cxf.wsdl11.ServiceWSDLBuilderTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSchemas() throws Exception {
setupWSDL(WSDL_PATH);
Types types=newDef.getTypes();
assertNotNull(types);
Collection schemas=CastUtils.cast(types.getExtensibilityElements(),ExtensibilityElement.class);
assertEquals(1,schemas.size());
XmlSchemaCollection schemaCollection=new XmlSchemaCollection();
Element schemaElem=((Schema)schemas.iterator().next()).getElement();
XmlSchema newSchema=schemaCollection.read(schemaElem);
assertEquals("http://apache.org/hello_world_soap_http/types",newSchema.getTargetNamespace());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGreetMeOperation() throws Exception {
setupWSDL(WSDL_PATH);
PortType portType=newDef.getPortType(new QName(newDef.getTargetNamespace(),"Greeter"));
Operation greetMe=portType.getOperation("greetMe","greetMeRequest","greetMeResponse");
assertNotNull(greetMe);
assertEquals("greetMe",greetMe.getName());
Input input=greetMe.getInput();
assertNotNull(input);
assertEquals("greetMeRequest",input.getName());
Message message=input.getMessage();
assertNotNull(message);
assertEquals("greetMeRequest",message.getQName().getLocalPart());
assertEquals(newDef.getTargetNamespace(),message.getQName().getNamespaceURI());
assertEquals(1,message.getParts().size());
assertEquals("in",message.getPart("in").getName());
Output output=greetMe.getOutput();
assertNotNull(output);
assertEquals("greetMeResponse",output.getName());
message=output.getMessage();
assertNotNull(message);
assertEquals("greetMeResponse",message.getQName().getLocalPart());
assertEquals(newDef.getTargetNamespace(),message.getQName().getNamespaceURI());
assertEquals(1,message.getParts().size());
assertEquals("out",message.getPart("out").getName());
assertEquals(0,greetMe.getFaults().size());
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testXsdImportMultipleSchemas() throws Exception {
setupWSDL(WSDL_XSD_IMPORT_PATH,true);
Types types=newDef.getTypes();
assertNotNull(types);
Collection schemas=CastUtils.cast(types.getExtensibilityElements(),ExtensibilityElement.class);
assertEquals(1,schemas.size());
Schema schema=(Schema)schemas.iterator().next();
assertEquals(1,schema.getImports().values().size());
SchemaImport serviceTypesSchemaImport=getImport(schema.getImports(),"http://apache.org/hello_world_soap_http/servicetypes");
Schema serviceTypesSchema=serviceTypesSchemaImport.getReferencedSchema();
assertEquals(1,serviceTypesSchema.getImports().values().size());
SchemaImport typesSchemaImport=getImport(serviceTypesSchema.getImports(),"http://apache.org/hello_world_soap_http/types");
Schema typesSchema=typesSchemaImport.getReferencedSchema();
Document doc=typesSchema.getElement().getOwnerDocument();
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
XMLStreamWriter writer=StaxUtils.createXMLStreamWriter(outputStream,"utf-8");
StaxUtils.writeNode(doc,writer,true);
writer.close();
String savedSchema=new String(outputStream.toByteArray(),StandardCharsets.UTF_8);
assertTrue(savedSchema.contains("http://www.w3.org/2005/05/xmlmime"));
SchemaImport types2SchemaImport=getImport(typesSchema.getImports(),"http://apache.org/hello_world_soap_http/types2");
Schema types2Schema=types2SchemaImport.getReferencedSchema();
assertNotNull(types2Schema);
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSayHiOperation() throws Exception {
setupWSDL(WSDL_PATH);
PortType portType=newDef.getPortType(new QName(newDef.getTargetNamespace(),"Greeter"));
Collection operations=CastUtils.cast(portType.getOperations(),Operation.class);
assertEquals(4,operations.size());
Operation sayHi=portType.getOperation("sayHi","sayHiRequest","sayHiResponse");
assertNotNull(sayHi);
assertEquals(sayHi.getName(),"sayHi");
Input input=sayHi.getInput();
assertNotNull(input);
assertEquals("sayHiRequest",input.getName());
Message message=input.getMessage();
assertNotNull(message);
assertEquals("sayHiRequest",message.getQName().getLocalPart());
assertEquals(newDef.getTargetNamespace(),message.getQName().getNamespaceURI());
assertEquals(1,message.getParts().size());
assertEquals("in",message.getPart("in").getName());
Output output=sayHi.getOutput();
assertNotNull(output);
assertEquals("sayHiResponse",output.getName());
message=output.getMessage();
assertNotNull(message);
assertEquals("sayHiResponse",message.getQName().getLocalPart());
assertEquals(newDef.getTargetNamespace(),message.getQName().getNamespaceURI());
assertEquals(1,message.getParts().size());
assertEquals("out",message.getPart("out").getName());
assertEquals(0,sayHi.getFaults().size());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testPingMeOperation() throws Exception {
setupWSDL(WSDL_PATH);
PortType portType=newDef.getPortType(new QName(newDef.getTargetNamespace(),"Greeter"));
Operation pingMe=portType.getOperation("pingMe","pingMeRequest","pingMeResponse");
assertNotNull(pingMe);
assertEquals("pingMe",pingMe.getName());
Input input=pingMe.getInput();
assertNotNull(input);
assertEquals("pingMeRequest",input.getName());
Message message=input.getMessage();
assertNotNull(message);
assertEquals("pingMeRequest",message.getQName().getLocalPart());
assertEquals(newDef.getTargetNamespace(),message.getQName().getNamespaceURI());
assertEquals(1,message.getParts().size());
assertEquals("in",message.getPart("in").getName());
Output output=pingMe.getOutput();
assertNotNull(output);
assertEquals("pingMeResponse",output.getName());
message=output.getMessage();
assertNotNull(message);
assertEquals("pingMeResponse",message.getQName().getLocalPart());
assertEquals(newDef.getTargetNamespace(),message.getQName().getNamespaceURI());
assertEquals(message.getParts().size(),1);
assertEquals("out",message.getPart("out").getName());
assertEquals(1,pingMe.getFaults().size());
Fault fault=pingMe.getFault("pingMeFault");
assertNotNull(fault);
assertEquals("pingMeFault",fault.getName());
message=fault.getMessage();
assertNotNull(message);
assertEquals("pingMeFault",message.getQName().getLocalPart());
assertEquals(newDef.getTargetNamespace(),message.getQName().getNamespaceURI());
assertEquals(1,message.getParts().size());
assertEquals("faultDetail",message.getPart("faultDetail").getName());
assertNull(message.getPart("faultDetail").getTypeName());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testGreetMeOneWayOperation() throws Exception {
setupWSDL(WSDL_PATH);
PortType portType=newDef.getPortType(new QName(newDef.getTargetNamespace(),"Greeter"));
Operation greetMeOneWay=portType.getOperation("greetMeOneWay","greetMeOneWayRequest",null);
assertNotNull(greetMeOneWay);
assertEquals("greetMeOneWay",greetMeOneWay.getName());
Input input=greetMeOneWay.getInput();
assertNotNull(input);
assertEquals("greetMeOneWayRequest",input.getName());
Message message=input.getMessage();
assertNotNull(message);
assertEquals("greetMeOneWayRequest",message.getQName().getLocalPart());
assertEquals(newDef.getTargetNamespace(),message.getQName().getNamespaceURI());
assertEquals(1,message.getParts().size());
assertEquals("in",message.getPart("in").getName());
Output output=greetMeOneWay.getOutput();
assertNull(output);
assertEquals(0,greetMeOneWay.getFaults().size());
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testPortType() throws Exception {
setupWSDL(WSDL_PATH);
assertEquals(1,newDef.getPortTypes().size());
PortType portType=(PortType)newDef.getPortTypes().values().iterator().next();
assertNotNull(portType);
assertTrue(portType.getQName().equals(new QName(newDef.getTargetNamespace(),"Greeter")));
}
InternalCallVerifier NullVerifier
@Test public void testNoBodyParts() throws Exception {
setupWSDL(NO_BODY_PARTS_WSDL_PATH);
QName messageName=new QName("urn:org:apache:cxf:no_body_parts/wsdl","operation1Request");
Message message=newDef.getMessage(messageName);
Part part=message.getPart("mimeAttachment");
assertNotNull(part.getTypeName());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testDefinition() throws Exception {
setupWSDL(WSDL_PATH);
assertEquals(newDef.getTargetNamespace(),"http://apache.org/hello_world_soap_http");
Service serv=newDef.getService(new QName("http://apache.org/hello_world_soap_http","SOAPService"));
assertNotNull(serv);
assertNotNull(serv.getPort("SoapPort"));
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBinding() throws Exception {
setupWSDL(WSDL_PATH);
assertEquals(newDef.getBindings().size(),1);
Binding binding=newDef.getBinding(new QName(newDef.getTargetNamespace(),"Greeter_SOAPBinding"));
assertNotNull(binding);
assertEquals(4,binding.getBindingOperations().size());
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testBindingWithDifferentNamespaceImport() throws Exception {
setupWSDL("wsdl2/person.wsdl");
assertEquals(newDef.getBindings().size(),1);
assertTrue(newDef.getNamespace("ns3").equals("http://cxf.apache.org/samples/wsdl-first"));
}
Class: org.apache.cxf.wsdl11.WSDLManagerImplTest APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBuildImportedWSDL() throws Exception {
String wsdlUrl=getClass().getResource("hello_world_services.wsdl").toString();
WSDLManagerImpl builder=new WSDLManagerImpl();
Definition def=builder.getDefinition(wsdlUrl);
assertNotNull(def);
Map,?> services=def.getServices();
assertNotNull(services);
assertEquals(1,services.size());
String serviceQName="http://apache.org/hello_world/services";
Service service=(Service)services.get(new QName(serviceQName,"SOAPService"));
assertNotNull(service);
Map,?> ports=service.getPorts();
assertNotNull(ports);
assertEquals(1,ports.size());
Port port=service.getPort("SoapPort");
assertNotNull(port);
Binding binding=port.getBinding();
assertNotNull(binding);
QName bindingQName=new QName("http://apache.org/hello_world/bindings","SOAPBinding");
assertEquals(bindingQName,binding.getQName());
PortType portType=binding.getPortType();
assertNotNull(portType);
QName portTypeQName=new QName("http://apache.org/hello_world","Greeter");
assertEquals(portTypeQName,portType.getQName());
Operation op1=portType.getOperation("sayHi","sayHiRequest","sayHiResponse");
assertNotNull(op1);
QName messageQName=new QName("http://apache.org/hello_world/messages","sayHiRequest");
assertEquals(messageQName,op1.getInput().getMessage().getQName());
Part part=op1.getInput().getMessage().getPart("in");
assertNotNull(part);
assertEquals(new QName("http://apache.org/hello_world/types","sayHi"),part.getElementName());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBuildSimpleWSDL() throws Exception {
String qname="http://apache.org/hello_world_soap_http";
String wsdlUrl=getClass().getResource("hello_world.wsdl").toString();
WSDLManagerImpl builder=new WSDLManagerImpl();
Definition def=builder.getDefinition(wsdlUrl);
assertNotNull(def);
Map,?> services=def.getServices();
assertNotNull(services);
assertEquals(1,services.size());
Service service=(Service)services.get(new QName(qname,"SOAPService"));
assertNotNull(service);
Map,?> ports=service.getPorts();
assertNotNull(ports);
assertEquals(1,ports.size());
Port port=service.getPort("SoapPort");
assertNotNull(port);
}
Class: org.apache.cxf.wsdl11.WSDLServiceBuilderTest BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBindingMessageInfo() throws Exception {
setUpBasic();
BindingInfo bindingInfo=null;
bindingInfo=serviceInfo.getBindings().iterator().next();
QName name=new QName(serviceInfo.getName().getNamespaceURI(),"sayHi");
BindingOperationInfo sayHi=bindingInfo.getOperation(name);
BindingMessageInfo input=sayHi.getInput();
assertNotNull(input);
assertEquals(input.getMessageInfo().getName().getLocalPart(),"sayHiRequest");
assertEquals(input.getMessageInfo().getName().getNamespaceURI(),"http://apache.org/hello_world_soap_http");
assertEquals(input.getMessageInfo().getMessageParts().size(),1);
assertEquals(input.getMessageInfo().getMessageParts().get(0).getName().getLocalPart(),"in");
assertEquals(input.getMessageInfo().getMessageParts().get(0).getName().getNamespaceURI(),"http://apache.org/hello_world_soap_http");
assertTrue(input.getMessageInfo().getMessageParts().get(0).isElement());
QName elementName=input.getMessageInfo().getMessageParts().get(0).getElementQName();
assertEquals(elementName.getLocalPart(),"sayHi");
assertEquals(elementName.getNamespaceURI(),"http://apache.org/hello_world_soap_http/types");
BindingMessageInfo output=sayHi.getOutput();
assertNotNull(output);
assertEquals(output.getMessageInfo().getName().getLocalPart(),"sayHiResponse");
assertEquals(output.getMessageInfo().getName().getNamespaceURI(),"http://apache.org/hello_world_soap_http");
assertEquals(output.getMessageInfo().getMessageParts().size(),1);
assertEquals(output.getMessageInfo().getMessageParts().get(0).getName().getLocalPart(),"out");
assertEquals(output.getMessageInfo().getMessageParts().get(0).getName().getNamespaceURI(),"http://apache.org/hello_world_soap_http");
assertTrue(output.getMessageInfo().getMessageParts().get(0).isElement());
elementName=output.getMessageInfo().getMessageParts().get(0).getElementQName();
assertEquals(elementName.getLocalPart(),"sayHiResponse");
assertEquals(elementName.getNamespaceURI(),"http://apache.org/hello_world_soap_http/types");
assertTrue(sayHi.getFaults().size() == 0);
name=new QName(serviceInfo.getName().getNamespaceURI(),"pingMe");
BindingOperationInfo pingMe=bindingInfo.getOperation(name);
assertNotNull(pingMe);
assertEquals(1,pingMe.getFaults().size());
BindingFaultInfo fault=pingMe.getFaults().iterator().next();
assertNotNull(fault);
assertEquals(fault.getFaultInfo().getName().getLocalPart(),"pingMeFault");
assertEquals(fault.getFaultInfo().getName().getNamespaceURI(),"http://apache.org/hello_world_soap_http");
assertEquals(fault.getFaultInfo().getMessageParts().size(),1);
assertEquals(fault.getFaultInfo().getMessageParts().get(0).getName().getLocalPart(),"faultDetail");
assertEquals(fault.getFaultInfo().getMessageParts().get(0).getName().getNamespaceURI(),"http://apache.org/hello_world_soap_http");
assertTrue(fault.getFaultInfo().getMessageParts().get(0).isElement());
elementName=fault.getFaultInfo().getMessageParts().get(0).getElementQName();
assertEquals(elementName.getLocalPart(),"faultDetail");
assertEquals(elementName.getNamespaceURI(),"http://apache.org/hello_world_soap_http/types");
control.verify();
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBare() throws Exception {
setUpWSDL(BARE_WSDL_PATH,0);
BindingInfo bindingInfo=null;
bindingInfo=serviceInfo.getBindings().iterator().next();
Collection bindingOperationInfos=bindingInfo.getOperations();
assertNotNull(bindingOperationInfos);
assertEquals(bindingOperationInfos.size(),1);
LOG.info("the binding operation is " + bindingOperationInfos.iterator().next().getName());
QName name=new QName(serviceInfo.getName().getNamespaceURI(),"greetMe");
BindingOperationInfo greetMe=bindingInfo.getOperation(name);
assertNotNull(greetMe);
assertEquals("greetMe OperationInfo name error",greetMe.getName(),name);
assertFalse("greetMe should be a Unwrapped operation ",greetMe.isUnwrappedCapable());
assertNotNull(serviceInfo.getXmlSchemaCollection());
control.verify();
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testNoBodyParts() throws Exception {
setUpWSDL(NO_BODY_PARTS_WSDL_PATH,0);
QName messageName=new QName("urn:org:apache:cxf:no_body_parts/wsdl","operation1Request");
MessageInfo mi=serviceInfo.getMessage(messageName);
QName partName=new QName("urn:org:apache:cxf:no_body_parts/wsdl","mimeAttachment");
MessagePartInfo pi=mi.getMessagePart(partName);
QName typeName=new QName("http://www.w3.org/2001/XMLSchema","base64Binary");
assertEquals(typeName,pi.getTypeQName());
assertNull(pi.getElementQName());
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testExtensions() throws Exception {
setUpWSDL("hello_world_ext.wsdl",0);
String ns="http://apache.org/hello_world_soap_http";
QName pingMeOpName=new QName(ns,"pingMe");
QName greetMeOpName=new QName(ns,"greetMe");
QName faultName=new QName(ns,"pingMeFault");
InterfaceInfo ii=serviceInfo.getInterface();
assertEquals(2,ii.getExtensionAttributes().size());
assertNotNull(ii.getExtensionAttribute(EXTENSION_ATTR_BOOLEAN));
assertNotNull(ii.getExtensionAttribute(EXTENSION_ATTR_STRING));
assertEquals(1,ii.getExtensors(UnknownExtensibilityElement.class).size());
assertEquals(EXTENSION_ELEM,ii.getExtensor(UnknownExtensibilityElement.class).getElementType());
OperationInfo oi=ii.getOperation(pingMeOpName);
assertPortTypeOperationExtensions(oi,true);
assertPortTypeOperationExtensions(ii.getOperation(greetMeOpName),false);
assertPortTypeOperationMessageExtensions(oi,true,true,faultName);
assertPortTypeOperationMessageExtensions(ii.getOperation(greetMeOpName),false,true,null);
assertEquals(1,serviceInfo.getExtensionAttributes().size());
assertNotNull(serviceInfo.getExtensionAttribute(EXTENSION_ATTR_STRING));
assertEquals(1,serviceInfo.getExtensors(UnknownExtensibilityElement.class).size());
assertEquals(EXTENSION_ELEM,serviceInfo.getExtensor(UnknownExtensibilityElement.class).getElementType());
EndpointInfo ei=serviceInfo.getEndpoints().iterator().next();
assertEquals(1,ei.getExtensionAttributes().size());
assertNotNull(ei.getExtensionAttribute(EXTENSION_ATTR_STRING));
assertEquals(1,ei.getExtensors(UnknownExtensibilityElement.class).size());
assertEquals(EXTENSION_ELEM,ei.getExtensor(UnknownExtensibilityElement.class).getElementType());
BindingInfo bi=ei.getBinding();
assertEquals(1,bi.getExtensors(UnknownExtensibilityElement.class).size());
assertEquals(EXTENSION_ELEM,bi.getExtensor(UnknownExtensibilityElement.class).getElementType());
BindingOperationInfo boi=bi.getOperation(pingMeOpName);
assertBindingOperationExtensions(boi,true);
assertBindingOperationExtensions(bi.getOperation(greetMeOpName),false);
assertBindingOperationMessageExtensions(boi,true,true,faultName);
assertBindingOperationMessageExtensions(bi.getOperation(greetMeOpName),false,true,null);
control.verify();
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testServiceInfo() throws Exception {
setUpBasic();
assertEquals("SOAPService",serviceInfo.getName().getLocalPart());
assertEquals("http://apache.org/hello_world_soap_http",serviceInfo.getName().getNamespaceURI());
assertEquals("http://apache.org/hello_world_soap_http",serviceInfo.getTargetNamespace());
assertTrue(serviceInfo.getProperty(WSDLServiceBuilder.WSDL_DEFINITION) == def);
assertTrue(serviceInfo.getProperty(WSDLServiceBuilder.WSDL_SERVICE) == service);
assertEquals("Incorrect number of endpoints",1,serviceInfo.getEndpoints().size());
EndpointInfo ei=serviceInfo.getEndpoint(new QName("http://apache.org/hello_world_soap_http","SoapPort"));
assertNotNull(ei);
assertEquals("http://schemas.xmlsoap.org/wsdl/soap/",ei.getTransportId());
assertNotNull(ei.getBinding());
control.verify();
}
APIUtilityVerifier BranchVerifier UtilityVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testImport() throws Exception {
DocumentBuilder db=DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc=db.parse(this.getClass().getResourceAsStream("./s1/s2/schema2.xsd"));
Element schemaImport=null;
Node node=doc.getFirstChild();
while (node != null) {
if (node instanceof Element) {
schemaImport=DOMUtils.getFirstElement(node);
}
node=node.getNextSibling();
}
if (schemaImport == null) {
fail("Can't find import element");
}
String filePath=this.getClass().getResource("./s1/s2/s4/schema4.xsd").toURI().getPath();
String importPath=schemaImport.getAttributeNode("schemaLocation").getValue();
if (!new URI(URLEncoder.encode(importPath,"utf-8")).isAbsolute()) {
schemaImport.getAttributeNode("schemaLocation").setNodeValue("file:" + filePath);
String fileStr=this.getClass().getResource("./s1/s2/schema2.xsd").toURI().getPath();
fileStr=URLDecoder.decode(fileStr,"utf-8");
File file=new File(fileStr);
if (file.exists()) {
file.delete();
}
FileOutputStream fout=new FileOutputStream(file);
StaxUtils.writeTo(doc,fout);
fout.flush();
fout.close();
}
setUpWSDL(IMPORT_WSDL_PATH,0);
assertNotNull(serviceInfo.getSchemas());
Element ele=serviceInfo.getSchemas().iterator().next().getElement();
assertNotNull(ele);
Schema schema=EndpointReferenceUtils.getSchema(serviceInfo,null);
assertNotNull(schema);
control.verify();
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testParameterOrder2() throws Exception {
setUpWSDL("header2.wsdl",0);
String ns="http://apache.org/header2";
OperationInfo operation=serviceInfo.getInterface().getOperation(new QName(ns,"headerMethod"));
assertNotNull(operation);
List parts=operation.getInput().getMessageParts();
assertNotNull(parts);
assertEquals(2,parts.size());
assertEquals("header_info",parts.get(0).getName().getLocalPart());
assertEquals("the_request",parts.get(1).getName().getLocalPart());
control.verify();
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSchema() throws Exception {
setUpBasic();
SchemaCollection schemas=serviceInfo.getXmlSchemaCollection();
assertNotNull(schemas);
assertEquals(1,serviceInfo.getSchemas().size());
SchemaInfo schemaInfo=serviceInfo.getSchemas().iterator().next();
assertNotNull(schemaInfo);
assertEquals(schemaInfo.getNamespaceURI(),"http://apache.org/hello_world_soap_http/types");
assertEquals(schemas.read(schemaInfo.getElement()).getTargetNamespace(),"http://apache.org/hello_world_soap_http/types");
Schema schema=EndpointReferenceUtils.getSchema(serviceInfo);
assertNotNull(schema);
control.verify();
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testOperationInfo() throws Exception {
setUpBasic();
QName name=new QName(serviceInfo.getName().getNamespaceURI(),"sayHi");
assertEquals(4,serviceInfo.getInterface().getOperations().size());
OperationInfo sayHi=serviceInfo.getInterface().getOperation(new QName(serviceInfo.getName().getNamespaceURI(),"sayHi"));
assertNotNull(sayHi);
assertEquals(sayHi.getName(),name);
assertFalse(sayHi.isOneWay());
assertTrue(sayHi.hasInput());
assertTrue(sayHi.hasOutput());
assertNull(sayHi.getParameterOrdering());
name=new QName(serviceInfo.getName().getNamespaceURI(),"greetMe");
OperationInfo greetMe=serviceInfo.getInterface().getOperation(name);
assertNotNull(greetMe);
assertEquals(greetMe.getName(),name);
assertFalse(greetMe.isOneWay());
assertTrue(greetMe.hasInput());
assertTrue(greetMe.hasOutput());
List inParts=greetMe.getInput().getMessageParts();
assertEquals(1,inParts.size());
MessagePartInfo part=inParts.get(0);
assertNotNull(part.getXmlSchema());
assertTrue(part.getXmlSchema() instanceof XmlSchemaElement);
List outParts=greetMe.getOutput().getMessageParts();
assertEquals(1,outParts.size());
part=outParts.get(0);
assertNotNull(part.getXmlSchema());
assertTrue(part.getXmlSchema() instanceof XmlSchemaElement);
assertTrue("greatMe should be wrapped",greetMe.isUnwrappedCapable());
OperationInfo greetMeUnwrapped=greetMe.getUnwrappedOperation();
assertNotNull(greetMeUnwrapped.getInput());
assertNotNull(greetMeUnwrapped.getOutput());
assertEquals("wrapped part not set",1,greetMeUnwrapped.getInput().size());
assertEquals("wrapped part not set",1,greetMeUnwrapped.getOutput().size());
assertEquals("wrapper part name wrong","requestType",greetMeUnwrapped.getInput().getMessagePartByIndex(0).getName().getLocalPart());
assertEquals("wrapper part type name wrong","MyStringType",greetMeUnwrapped.getInput().getMessagePartByIndex(0).getTypeQName().getLocalPart());
assertEquals("wrapper part name wrong","responseType",greetMeUnwrapped.getOutput().getMessagePartByIndex(0).getName().getLocalPart());
assertEquals("wrapper part type name wrong","string",greetMeUnwrapped.getOutput().getMessagePartByIndex(0).getTypeQName().getLocalPart());
name=new QName(serviceInfo.getName().getNamespaceURI(),"greetMeOneWay");
OperationInfo greetMeOneWay=serviceInfo.getInterface().getOperation(name);
assertNotNull(greetMeOneWay);
assertEquals(greetMeOneWay.getName(),name);
assertTrue(greetMeOneWay.isOneWay());
assertTrue(greetMeOneWay.hasInput());
assertFalse(greetMeOneWay.hasOutput());
OperationInfo greetMeOneWayUnwrapped=greetMeOneWay.getUnwrappedOperation();
assertNotNull(greetMeOneWayUnwrapped);
assertNotNull(greetMeOneWayUnwrapped.getInput());
assertNull(greetMeOneWayUnwrapped.getOutput());
assertEquals("wrapped part not set",1,greetMeOneWayUnwrapped.getInput().size());
assertEquals(new QName("http://apache.org/hello_world_soap_http/types","requestType"),greetMeOneWayUnwrapped.getInput().getMessagePartByIndex(0).getConcreteName());
name=new QName(serviceInfo.getName().getNamespaceURI(),"pingMe");
OperationInfo pingMe=serviceInfo.getInterface().getOperation(name);
assertNotNull(pingMe);
assertEquals(pingMe.getName(),name);
assertFalse(pingMe.isOneWay());
assertTrue(pingMe.hasInput());
assertTrue(pingMe.hasOutput());
assertNull(serviceInfo.getInterface().getOperation(new QName("what ever")));
control.verify();
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testParameterOrder() throws Exception {
String ns="http://apache.org/hello_world_xml_http/bare";
setUpWSDL("hello_world_xml_bare.wsdl",0);
OperationInfo operation=serviceInfo.getInterface().getOperation(new QName(ns,"testTriPart"));
assertNotNull(operation);
List parts=operation.getInput().getMessageParts();
assertNotNull(parts);
assertEquals(3,parts.size());
assertEquals("in3",parts.get(0).getName().getLocalPart());
assertEquals("in1",parts.get(1).getName().getLocalPart());
assertEquals("in2",parts.get(2).getName().getLocalPart());
List order=operation.getParameterOrdering();
assertNotNull(order);
assertEquals(3,order.size());
assertEquals("in1",order.get(0));
assertEquals("in3",order.get(1));
assertEquals("in2",order.get(2));
parts=operation.getInput().getOrderedParts(order);
assertNotNull(parts);
assertEquals(3,parts.size());
assertEquals("in1",parts.get(0).getName().getLocalPart());
assertEquals("in3",parts.get(1).getName().getLocalPart());
assertEquals("in2",parts.get(2).getName().getLocalPart());
operation=serviceInfo.getInterface().getOperation(new QName(ns,"testTriPartNoOrder"));
assertNotNull(operation);
parts=operation.getInput().getMessageParts();
assertNotNull(parts);
assertEquals(3,parts.size());
assertEquals("in3",parts.get(0).getName().getLocalPart());
assertEquals("in1",parts.get(1).getName().getLocalPart());
assertEquals("in2",parts.get(2).getName().getLocalPart());
control.verify();
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBindingOperationInfo() throws Exception {
setUpBasic();
BindingInfo bindingInfo=null;
bindingInfo=serviceInfo.getBindings().iterator().next();
Collection bindingOperationInfos=bindingInfo.getOperations();
assertNotNull(bindingOperationInfos);
assertEquals(bindingOperationInfos.size(),4);
LOG.info("the binding operation is " + bindingOperationInfos.iterator().next().getName());
QName name=new QName(serviceInfo.getName().getNamespaceURI(),"sayHi");
BindingOperationInfo sayHi=bindingInfo.getOperation(name);
assertNotNull(sayHi);
assertEquals(sayHi.getName(),name);
name=new QName(serviceInfo.getName().getNamespaceURI(),"greetMe");
BindingOperationInfo greetMe=bindingInfo.getOperation(name);
assertNotNull(greetMe);
assertEquals(greetMe.getName(),name);
name=new QName(serviceInfo.getName().getNamespaceURI(),"greetMeOneWay");
BindingOperationInfo greetMeOneWay=bindingInfo.getOperation(name);
assertNotNull(greetMeOneWay);
assertEquals(greetMeOneWay.getName(),name);
name=new QName(serviceInfo.getName().getNamespaceURI(),"pingMe");
BindingOperationInfo pingMe=bindingInfo.getOperation(name);
assertNotNull(pingMe);
assertEquals(pingMe.getName(),name);
control.verify();
}
InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testBindingInfo() throws Exception {
setUpBasic();
BindingInfo bindingInfo=null;
assertEquals(1,serviceInfo.getBindings().size());
bindingInfo=serviceInfo.getBindings().iterator().next();
assertNotNull(bindingInfo);
assertEquals(bindingInfo.getInterface().getName().getLocalPart(),"Greeter");
assertEquals(bindingInfo.getName().getLocalPart(),"Greeter_SOAPBinding");
assertEquals(bindingInfo.getName().getNamespaceURI(),"http://apache.org/hello_world_soap_http");
control.verify();
}
Class: org.apache.cxf.wsn.WsnBrokerTest InternalCallVerifier EqualityVerifier PublicFieldVerifier
@Test public void testPublisher() throws Exception {
TestConsumer consumerCallback=new TestConsumer();
Consumer consumer=new Consumer(consumerCallback,"http://localhost:" + port2 + "/test/consumer");
Subscription subscription=notificationBroker.subscribe(consumer,"myTopic");
PublisherCallback publisherCallback=new PublisherCallback();
Publisher publisher=new Publisher(publisherCallback,"http://localhost:" + port2 + "/test/publisher");
Registration registration=notificationBroker.registerPublisher(publisher,"myTopic");
synchronized (consumerCallback.notifications) {
notificationBroker.notify(publisher,"myTopic",new JAXBElement(new QName("urn:test:org","foo"),String.class,"bar"));
consumerCallback.notifications.wait(1000000);
}
assertEquals(1,consumerCallback.notifications.size());
NotificationMessageHolderType message=consumerCallback.notifications.get(0);
assertEquals(WSNHelper.getInstance().getWSAAddress(subscription.getEpr()),WSNHelper.getInstance().getWSAAddress(message.getSubscriptionReference()));
assertEquals(WSNHelper.getInstance().getWSAAddress(publisher.getEpr()),WSNHelper.getInstance().getWSAAddress(message.getProducerReference()));
subscription.unsubscribe();
registration.destroy();
publisher.stop();
consumer.stop();
}
InternalCallVerifier EqualityVerifier PublicFieldVerifier
@Test public void testBroker() throws Exception {
TestConsumer callback=new TestConsumer();
Consumer consumer=new Consumer(callback,"http://localhost:" + port2 + "/test/consumer");
Subscription subscription=notificationBroker.subscribe(consumer,"myTopic");
synchronized (callback.notifications) {
notificationBroker.notify("myTopic",new JAXBElement(new QName("urn:test:org","foo"),String.class,"bar"));
callback.notifications.wait(1000000);
}
assertEquals(1,callback.notifications.size());
NotificationMessageHolderType message=callback.notifications.get(0);
assertEquals(WSNHelper.getInstance().getWSAAddress(subscription.getEpr()),WSNHelper.getInstance().getWSAAddress(message.getSubscriptionReference()));
subscription.unsubscribe();
consumer.stop();
}
BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier PublicFieldVerifier HybridVerifier
@Test public void testPublisherCustomType() throws Exception {
notificationBroker.setExtraClasses(CustomType.class);
TestConsumer consumerCallback=new TestConsumer();
Consumer consumer=new Consumer(consumerCallback,"http://localhost:" + port2 + "/test/consumer",CustomType.class);
Subscription subscription=notificationBroker.subscribe(consumer,"myTopic");
PublisherCallback publisherCallback=new PublisherCallback();
Publisher publisher=new Publisher(publisherCallback,"http://localhost:" + port2 + "/test/publisher");
Registration registration=notificationBroker.registerPublisher(publisher,"myTopic");
synchronized (consumerCallback.notifications) {
notificationBroker.notify(publisher,"myTopic",new CustomType(1,2));
consumerCallback.notifications.wait(1000000);
}
assertEquals(1,consumerCallback.notifications.size());
NotificationMessageHolderType message=consumerCallback.notifications.get(0);
assertEquals(WSNHelper.getInstance().getWSAAddress(subscription.getEpr()),WSNHelper.getInstance().getWSAAddress(message.getSubscriptionReference()));
assertEquals(WSNHelper.getInstance().getWSAAddress(publisher.getEpr()),WSNHelper.getInstance().getWSAAddress(message.getProducerReference()));
assertNotNull(message.getMessage().getAny());
assertTrue(message.getMessage().getAny().getClass().getName(),message.getMessage().getAny() instanceof CustomType);
subscription.unsubscribe();
registration.destroy();
publisher.stop();
consumer.stop();
}
InternalCallVerifier EqualityVerifier PublicFieldVerifier
@Test public void testNullPublisherReference() throws Exception {
TestConsumer consumerCallback=new TestConsumer();
Consumer consumer=new Consumer(consumerCallback,"http://localhost:" + port2 + "/test/consumer");
Subscription subscription=notificationBroker.subscribe(consumer,"myTopicNullEPR");
Publisher publisher=new Publisher(null,null);
Registration registration=notificationBroker.registerPublisher(publisher,"myTopicNullEPR",false);
synchronized (consumerCallback.notifications) {
notificationBroker.notify(publisher,"myTopicNullEPR",new JAXBElement(new QName("urn:test:org","foo"),String.class,"bar"));
consumerCallback.notifications.wait(1000000);
}
assertEquals(1,consumerCallback.notifications.size());
NotificationMessageHolderType message=consumerCallback.notifications.get(0);
assertEquals(WSNHelper.getInstance().getWSAAddress(subscription.getEpr()),WSNHelper.getInstance().getWSAAddress(message.getSubscriptionReference()));
subscription.unsubscribe();
registration.destroy();
publisher.stop();
consumer.stop();
}
Class: org.apache.cxf.xkms.itests.handlers.validator.ValidatorCRLTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testRevokedCertificate() throws CertificateException {
X509Certificate wss40Certificate=readCertificate("wss40rev.cer");
ValidateRequestType request=prepareValidateXKMSRequest(wss40Certificate);
StatusType result=doValidate(request);
Assert.assertEquals(KeyBindingEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_INVALID,result.getStatusValue());
Assert.assertFalse(result.getInvalidReason().isEmpty());
Assert.assertEquals(ReasonEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_ISSUER_TRUST.value(),result.getInvalidReason().get(0));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testValidCertWithCRL() throws CertificateException {
X509Certificate wss40Certificate=readCertificate("wss40.cer");
ValidateRequestType request=prepareValidateXKMSRequest(wss40Certificate);
StatusType result=doValidate(request);
Assert.assertEquals(KeyBindingEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_VALID,result.getStatusValue());
Assert.assertFalse(result.getValidReason().isEmpty());
Assert.assertEquals(ReasonEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_VALIDITY_INTERVAL.value(),result.getValidReason().get(0));
Assert.assertEquals(ReasonEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_ISSUER_TRUST.value(),result.getValidReason().get(1));
}
Class: org.apache.cxf.xkms.itests.handlers.validator.ValidatorTest APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testWss40DirectTrustNegative() throws JAXBException, CertificateException {
X509Certificate wss40Certificate=readCertificate("wss40.cer");
ValidateRequestType request=prepareValidateXKMSRequest(wss40Certificate);
request.getQueryKeyBinding().getKeyUsage().add(KeyUsageEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_SIGNATURE);
StatusType result=doValidate(request);
Assert.assertEquals(KeyBindingEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_INVALID,result.getStatusValue());
Assert.assertFalse(result.getInvalidReason().isEmpty());
Assert.assertEquals(XKMSConstants.DIRECT_TRUST_VALIDATION,result.getInvalidReason().get(0));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testDaveSignedByAliceSginedByRootIsValid() throws JAXBException, CertificateException {
X509Certificate daveCertificate=readCertificate("dave.cer");
ValidateRequestType request=prepareValidateXKMSRequest(daveCertificate);
StatusType result=doValidate(request);
Assert.assertEquals(KeyBindingEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_VALID,result.getStatusValue());
Assert.assertFalse(result.getValidReason().isEmpty());
Assert.assertEquals(ReasonEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_VALIDITY_INTERVAL.value(),result.getValidReason().get(0));
Assert.assertEquals(ReasonEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_ISSUER_TRUST.value(),result.getValidReason().get(1));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testSelfSignedCertOscarIsNotValid() throws JAXBException, CertificateException {
X509Certificate oscarCertificate=readCertificate("oscar.cer");
ValidateRequestType request=prepareValidateXKMSRequest(oscarCertificate);
StatusType result=doValidate(request);
Assert.assertEquals(KeyBindingEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_INVALID,result.getStatusValue());
Assert.assertFalse(result.getInvalidReason().isEmpty());
Assert.assertEquals(ReasonEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_ISSUER_TRUST.value(),result.getInvalidReason().get(0));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testRootCertIsValid() throws CertificateException {
X509Certificate rootCertificate=readCertificate("trusted_cas/root.cer");
ValidateRequestType request=prepareValidateXKMSRequest(rootCertificate);
StatusType result=doValidate(request);
Assert.assertEquals(KeyBindingEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_VALID,result.getStatusValue());
Assert.assertFalse(result.getValidReason().isEmpty());
Assert.assertEquals(ReasonEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_VALIDITY_INTERVAL.value(),result.getValidReason().get(0));
Assert.assertEquals(ReasonEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_ISSUER_TRUST.value(),result.getValidReason().get(1));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testDaveDirectTrust() throws JAXBException, CertificateException {
X509Certificate daveCertificate=readCertificate("dave.cer");
ValidateRequestType request=prepareValidateXKMSRequest(daveCertificate);
request.getQueryKeyBinding().getKeyUsage().add(KeyUsageEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_SIGNATURE);
StatusType result=doValidate(request);
Assert.assertEquals(KeyBindingEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_VALID,result.getStatusValue());
Assert.assertFalse(result.getValidReason().isEmpty());
Assert.assertEquals(ReasonEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_VALIDITY_INTERVAL.value(),result.getValidReason().get(0));
Assert.assertEquals(ReasonEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_ISSUER_TRUST.value(),result.getValidReason().get(1));
Assert.assertEquals(XKMSConstants.DIRECT_TRUST_VALIDATION,result.getValidReason().get(2));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testAliceSignedByRootIsValid() throws JAXBException, CertificateException {
X509Certificate aliceCertificate=readCertificate("cas/alice.cer");
ValidateRequestType request=prepareValidateXKMSRequest(aliceCertificate);
StatusType result=doValidate(request);
Assert.assertEquals(KeyBindingEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_VALID,result.getStatusValue());
Assert.assertFalse(result.getValidReason().isEmpty());
Assert.assertEquals(ReasonEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_VALIDITY_INTERVAL.value(),result.getValidReason().get(0));
Assert.assertEquals(ReasonEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_ISSUER_TRUST.value(),result.getValidReason().get(1));
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testExpiredCertIsNotValid() throws CertificateException {
X509Certificate expiredCertificate=readCertificate("expired.cer");
ValidateRequestType request=prepareValidateXKMSRequest(expiredCertificate);
StatusType result=doValidate(request);
Assert.assertEquals(KeyBindingEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_INVALID,result.getStatusValue());
Assert.assertFalse(result.getInvalidReason().isEmpty());
Assert.assertEquals(ReasonEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_VALIDITY_INTERVAL.value(),result.getInvalidReason().get(0));
}
Class: org.apache.cxf.xkms.itests.service.XKMSServiceTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testEmptyRegister() throws URISyntaxException, Exception {
RegisterRequestType request=new RegisterRequestType();
setGenericRequestParams(request);
RegisterResultType result=xkmsService.register(request);
Assert.assertEquals(ResultMajorEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_SENDER.value(),result.getResultMajor());
Assert.assertEquals(ResultMinorEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_FAILURE.value(),result.getResultMinor());
ResultDetails message=(ResultDetails)result.getMessageExtension().get(0);
Assert.assertEquals("org.apache.cxf.xkms.model.xkms.PrototypeKeyBindingType must be set",message.getDetails());
}
APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testRegisterWithoutKey() throws URISyntaxException, Exception {
RegisterRequestType request=new RegisterRequestType();
setGenericRequestParams(request);
PrototypeKeyBindingType binding=new PrototypeKeyBindingType();
KeyInfoType keyInfo=new KeyInfoType();
binding.setKeyInfo(keyInfo);
request.setPrototypeKeyBinding(binding);
RegisterResultType result=xkmsService.register(request);
Assert.assertEquals(ResultMajorEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_SENDER.value(),result.getResultMajor());
Assert.assertEquals(ResultMinorEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_FAILURE.value(),result.getResultMinor());
}
Class: org.apache.cxf.xkms.itests.service.XKRSSDisableTest APIUtilityVerifier InternalCallVerifier EqualityVerifier
@Test public void testRegisterShouldBeDisabled(){
RegisterRequestType request=new RegisterRequestType();
request.setService(XKMSConstants.XKMS_ENDPOINT_NAME);
request.setId(UUID.randomUUID().toString());
RegisterResultType result=xkmsService.register(request);
Assert.assertEquals(ResultMajorEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_SENDER.value(),result.getResultMajor());
Assert.assertEquals(ResultMinorEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_MESSAGE_NOT_SUPPORTED.value(),result.getResultMinor());
ResultDetails message=(ResultDetails)result.getMessageExtension().get(0);
Assert.assertEquals("XKRSS Operations are disabled",message.getDetails());
}
Class: org.apache.cxf.xkms.x509.handlers.X509LocatorTest InternalCallVerifier NullVerifier
@Test public void locate() throws CertificateException {
CertificateRepo certRepo=EasyMock.createMock(CertificateRepo.class);
EasyMock.expect(certRepo.findBySubjectDn(EasyMock.eq("alice"))).andReturn(getAliceCert());
EasyMock.replay(certRepo);
X509Locator locator=new X509Locator(certRepo);
LocateRequestType request=prepareLocateXKMSRequest();
UnverifiedKeyBindingType result=locator.locate(request);
Assert.assertNotNull(result.getKeyInfo());
}
Class: org.apache.cxf.xkms.x509.repo.file.FileCertificateRepoTest InternalCallVerifier EqualityVerifier
@Test public void testConvertDnForFileSystem() throws CertificateException {
String convertedName=new FileCertificateRepo("src/test/resources/store1").convertIdForFileSystem(EXAMPLE_SUBJECT_DN);
Assert.assertEquals("CN-www.issuer.com_L-CGN_ST-NRW_C-DE_O-Issuer",convertedName);
}
BooleanVerifier InternalCallVerifier NullVerifier HybridVerifier
@Test public void testFindBySubjectName() throws CertificateException {
File storageDir=new File("src/test/resources/store1");
Assert.assertTrue(storageDir.exists());
Assert.assertTrue(storageDir.isDirectory());
FileCertificateRepo persistenceManager=new FileCertificateRepo("src/test/resources/store1");
X509Certificate resCert=persistenceManager.findBySubjectDn(EXAMPLE_SUBJECT_DN);
Assert.assertNotNull(resCert);
}
APIUtilityVerifier BooleanVerifier InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testSaveAndFind() throws CertificateException, IOException, URISyntaxException {
File storageDir=new File("target/teststore1");
storageDir.mkdirs();
FileCertificateRepo fileRegisterHandler=new FileCertificateRepo("target/teststore1");
InputStream is=this.getClass().getResourceAsStream("/store1/" + EXPECTED_CERT_FILE_NAME);
if (is == null) {
throw new RuntimeException("Can not find path " + is + " in classpath");
}
X509Certificate cert=loadTestCert(is);
UseKeyWithType key=new UseKeyWithType();
key.setApplication(Applications.PKIX.getUri());
key.setIdentifier(EXAMPLE_SUBJECT_DN);
fileRegisterHandler.saveCertificate(cert,key);
File certFile=new File(storageDir,fileRegisterHandler.getCertPath(cert,key));
Assert.assertTrue("Cert file " + certFile + " should exist",certFile.exists());
FileInputStream fis=new FileInputStream(certFile);
X509Certificate outCert=loadTestCert(fis);
Assert.assertEquals(cert,outCert);
X509Certificate resultCert=fileRegisterHandler.findBySubjectDn(EXAMPLE_SUBJECT_DN);
Assert.assertNotNull(resultCert);
}
Class: org.apache.cxf.xkms.x509.repo.ldap.LDAPCertificateRepoTest InternalCallVerifier EqualityVerifier IgnoredMethod HybridVerifier
@Test @Ignore public void testFindServiceCert() throws URISyntaxException, NamingException, CertificateException {
CertificateRepo persistenceManager=createLdapCertificateRepo();
String serviceUri="cn=http:\\/\\/myservice.apache.org\\/MyServiceName,ou=services";
X509Certificate cert=persistenceManager.findByServiceName(serviceUri);
Assert.assertEquals(EXPECTED_SUBJECT_DN,cert.getSubjectDN().toString());
}
InternalCallVerifier NullVerifier IgnoredMethod HybridVerifier
@Test @Ignore public void testFindUserCertForNonExistantDn() throws URISyntaxException, NamingException, CertificateException {
CertificateRepo persistenceManager=createLdapCertificateRepo();
X509Certificate cert=persistenceManager.findBySubjectDn("CN=wrong");
Assert.assertNull("Certifiacte should be null",cert);
}
Class: org.apache.cxf.xkms.x509.validator.DateValidatorTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void validateDateExpired() throws JAXBException {
StatusType result=processRequest("/validateRequestExpired.xml");
Assert.assertEquals(result.getStatusValue(),KeyBindingEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_INVALID);
Assert.assertFalse(result.getInvalidReason().isEmpty());
Assert.assertEquals(ReasonEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_VALIDITY_INTERVAL.value(),result.getInvalidReason().get(0));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void validateDateOK() throws JAXBException {
StatusType result=processRequest("/validateRequestOK.xml");
Assert.assertEquals(KeyBindingEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_VALID,result.getStatusValue());
Assert.assertFalse(result.getValidReason().isEmpty());
Assert.assertEquals(ReasonEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_VALIDITY_INTERVAL.value(),result.getValidReason().get(0));
}
Class: org.apache.cxf.xkms.x509.validator.TrustedAuthorityValidatorCRLTest BooleanVerifier InternalCallVerifier
@Test public void testIsCertChainValid() throws CertificateException {
TrustedAuthorityValidator validator=new TrustedAuthorityValidator(certificateRepo);
Assert.assertTrue("Root should be valid",validator.isCertificateChainValid(Arrays.asList(certificateRoot)));
Assert.assertTrue("wss40rev should not be valid",!validator.isCertificateChainValid(Arrays.asList(certificateWss40Rev)));
Assert.assertTrue("wss40 should be valid",validator.isCertificateChainValid(Arrays.asList(certificateWss40)));
}
Class: org.apache.cxf.xkms.x509.validator.TrustedAuthorityValidatorTest BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testSelfSignedCertOscarIsNotValid() throws JAXBException, CertificateException {
StatusType result=processRequest("validateRequestInvalidOscar.xml");
Assert.assertEquals(result.getStatusValue(),KeyBindingEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_INVALID);
Assert.assertFalse(result.getInvalidReason().isEmpty());
Assert.assertEquals(ReasonEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_ISSUER_TRUST.value(),result.getInvalidReason().get(0));
}
BooleanVerifier InternalCallVerifier
@Test public void testIsCertChainValid() throws CertificateException {
TrustedAuthorityValidator validator=new TrustedAuthorityValidator(certificateRepo);
Assert.assertTrue("Root should be valid",validator.isCertificateChainValid(Arrays.asList(certificateRoot)));
Assert.assertTrue("Alice should be valid",validator.isCertificateChainValid(Arrays.asList(certificateAlice)));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testRootCertIsValid() throws JAXBException, CertificateException {
StatusType result=processRequest("validateRequestOKRoot.xml");
Assert.assertEquals(KeyBindingEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_VALID,result.getStatusValue());
Assert.assertFalse(result.getValidReason().isEmpty());
Assert.assertEquals(ReasonEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_ISSUER_TRUST.value(),result.getValidReason().get(0));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testAliceSignedByRootIsValid() throws JAXBException, CertificateException {
StatusType result=processRequest("validateRequestOKAlice.xml");
Assert.assertEquals(KeyBindingEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_VALID,result.getStatusValue());
Assert.assertFalse(result.getValidReason().isEmpty());
Assert.assertEquals(ReasonEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_ISSUER_TRUST.value(),result.getValidReason().get(0));
}
BooleanVerifier InternalCallVerifier EqualityVerifier HybridVerifier
@Test public void testDaveSignedByAliceSginedByRootIsValid() throws JAXBException, CertificateException {
StatusType result=processRequest("validateRequestOKDave.xml");
Assert.assertEquals(KeyBindingEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_VALID,result.getStatusValue());
Assert.assertFalse(result.getValidReason().isEmpty());
Assert.assertEquals(ReasonEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_ISSUER_TRUST.value(),result.getValidReason().get(0));
}
Class: org.apache.cxf.xmlbeans.WrappedStyleTest InternalCallVerifier EqualityVerifier NullVerifier HybridVerifier
@Test public void testParams() throws Exception {
String ns="urn:TestService";
OperationInfo op=endpoint.getEndpoint().getService().getServiceInfos().get(0).getInterface().getOperation(new QName(ns,"GetWeatherByZipCode"));
assertNotNull(op);
MessagePartInfo info=op.getUnwrappedOperation().getInput().getMessagePart(0);
assertEquals(new QName("http://cxf.apache.org/xmlbeans","request"),info.getElementQName());
}
APIUtilityVerifier IterativeVerifier BooleanVerifier InternalCallVerifier
@Test public void testWSDL() throws Exception {
Node wsdl=getWSDLDocument("TestService");
addNamespace("xsd",Constants.URI_2001_SCHEMA_XSD);
addNamespace("ns0","http://cxf.apache.org/xmlbeans");
assertValid("//xsd:schema[@targetNamespace='urn:TestService']" + "/xsd:complexType[@name='mixedRequest']" + "//xsd:element[@name='string'][@type='xsd:string']",wsdl);
NodeList list=assertValid("//xsd:schema[@targetNamespace='urn:TestService']" + "/xsd:complexType[@name='mixedRequest']" + "//xsd:element[@ref]",wsdl);
for (int x=0; x < list.getLength(); x++) {
Element el=(Element)list.item(x);
assertTrue(el.getAttribute("ref"),el.getAttribute("ref").contains("request"));
}
assertValid("//xsd:schema[@targetNamespace='urn:TestService']" + "/xsd:element[@name='CustomFault'][@type='xsd:string']",wsdl);
}